From 7d24c25e851b2e7495b34641cedbd6df9748afeb Mon Sep 17 00:00:00 2001 From: Owlbot Bootstrapper Date: Thu, 24 Aug 2023 20:48:10 +0000 Subject: [PATCH 1/4] feat: initial commit From bc3f7839822a91869b5c84b4f8640019473d8972 Mon Sep 17 00:00:00 2001 From: Owlbot Bootstrapper Date: Thu, 24 Aug 2023 20:48:58 +0000 Subject: [PATCH 2/4] feat: initial generation of library Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLXdvcmtzdGF0aW9ucy8uT3dsQm90LnlhbWwiLCJoIjoiNTZjMTY2NTdlN2E1OTEyMmIxZGE5NDc3MWE5ZWY0MDk4OWMyODJjMCJ9 --- .../.repo-metadata.json | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/packages/google-cloud-workstations/.repo-metadata.json b/packages/google-cloud-workstations/.repo-metadata.json index 0f6aec78a046..c6bad5c429f8 100644 --- a/packages/google-cloud-workstations/.repo-metadata.json +++ b/packages/google-cloud-workstations/.repo-metadata.json @@ -1,17 +1,17 @@ { - "name": "workstations", - "name_pretty": "Cloud Workstations API", - "api_description": "Cloud Workstations API", - "product_documentation": "https://cloud.google.com/workstations/docs", - "client_documentation": "https://cloud.google.com/python/docs/reference/workstations/latest", - "issue_tracker": "https://issuetracker.google.com/issues/new?component=1328344", - "release_level": "preview", - "language": "python", - "library_type": "GAPIC_AUTO", - "repo": "googleapis/google-cloud-python", - "distribution_name": "google-cloud-workstations", - "api_id": "workstations.googleapis.com", - "default_version": "v1", - "codeowner_team": "", - "api_shortname": "workstations" + "name": "workstations", + "name_pretty": "Cloud Workstations", + "api_description": "", + "product_documentation": "https://cloud.google.com/workstations/", + "client_documentation": "https://cloud.google.com/python/docs/reference/workstations/latest", + "issue_tracker": "https://github.com/googleapis/google-cloud-python/issues", + "release_level": "preview", + "language": "python", + "library_type": "GAPIC_AUTO", + "repo": "googleapis/google-cloud-python", + "distribution_name": "google-cloud-workstations", + "api_id": "workstations.googleapis.com", + "default_version": "v1", + "codeowner_team": "", + "api_shortname": "workstations" } From f419f191bc78d79a6268d556b4e9e43166113f18 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 24 Aug 2023 20:54:21 +0000 Subject: [PATCH 3/4] Owl Bot copied code from https://github.com/googleapis/googleapis-gen/commit/56c16657e7a59122b1da94771a9ef40989c282c0 --- .../google-cloud-workstations/v1/.coveragerc | 13 + .../google-cloud-workstations/v1/.flake8 | 33 + .../google-cloud-workstations/v1/MANIFEST.in | 2 + .../google-cloud-workstations/v1/README.rst | 49 + .../google-cloud-workstations/v1/docs/conf.py | 376 + .../v1/docs/index.rst | 7 + .../v1/docs/workstations_v1/services.rst | 6 + .../v1/docs/workstations_v1/types.rst | 6 + .../v1/docs/workstations_v1/workstations.rst | 10 + .../v1/google/cloud/workstations/__init__.py | 87 + .../cloud/workstations/gapic_version.py | 16 + .../v1/google/cloud/workstations/py.typed | 2 + .../google/cloud/workstations_v1/__init__.py | 88 + .../cloud/workstations_v1/gapic_metadata.json | 328 + .../cloud/workstations_v1/gapic_version.py | 16 + .../v1/google/cloud/workstations_v1/py.typed | 2 + .../workstations_v1/services/__init__.py | 15 + .../services/workstations/__init__.py | 22 + .../services/workstations/async_client.py | 3093 ++++ .../services/workstations/client.py | 3259 ++++ .../services/workstations/pagers.py | 623 + .../workstations/transports/__init__.py | 38 + .../services/workstations/transports/base.py | 545 + .../services/workstations/transports/grpc.py | 943 ++ .../workstations/transports/grpc_asyncio.py | 942 ++ .../services/workstations/transports/rest.py | 3177 ++++ .../cloud/workstations_v1/types/__init__.py | 80 + .../workstations_v1/types/workstations.py | 1722 ++ .../google-cloud-workstations/v1/mypy.ini | 3 + .../google-cloud-workstations/v1/noxfile.py | 184 + ...metadata_google.cloud.workstations.v1.json | 3307 ++++ ...d_workstations_create_workstation_async.py | 57 + ...ations_create_workstation_cluster_async.py | 57 + ...tations_create_workstation_cluster_sync.py | 57 + ...tations_create_workstation_config_async.py | 57 + ...stations_create_workstation_config_sync.py | 57 + ...ed_workstations_create_workstation_sync.py | 57 + ...d_workstations_delete_workstation_async.py | 56 + ...ations_delete_workstation_cluster_async.py | 56 + ...tations_delete_workstation_cluster_sync.py | 56 + ...tations_delete_workstation_config_async.py | 56 + ...stations_delete_workstation_config_sync.py | 56 + ...ed_workstations_delete_workstation_sync.py | 56 + ...orkstations_generate_access_token_async.py | 52 + ...workstations_generate_access_token_sync.py | 52 + ...ated_workstations_get_workstation_async.py | 52 + ...kstations_get_workstation_cluster_async.py | 52 + ...rkstations_get_workstation_cluster_sync.py | 52 + ...rkstations_get_workstation_config_async.py | 52 + ...orkstations_get_workstation_config_sync.py | 52 + ...rated_workstations_get_workstation_sync.py | 52 + ...s_list_usable_workstation_configs_async.py | 53 + ...ns_list_usable_workstation_configs_sync.py | 53 + ...stations_list_usable_workstations_async.py | 53 + ...kstations_list_usable_workstations_sync.py | 53 + ...tations_list_workstation_clusters_async.py | 53 + ...stations_list_workstation_clusters_sync.py | 53 + ...stations_list_workstation_configs_async.py | 53 + ...kstations_list_workstation_configs_sync.py | 53 + ...ed_workstations_list_workstations_async.py | 53 + ...ted_workstations_list_workstations_sync.py | 53 + ...ed_workstations_start_workstation_async.py | 56 + ...ted_workstations_start_workstation_sync.py | 56 + ...ted_workstations_stop_workstation_async.py | 56 + ...ated_workstations_stop_workstation_sync.py | 56 + ...d_workstations_update_workstation_async.py | 55 + ...ations_update_workstation_cluster_async.py | 55 + ...tations_update_workstation_cluster_sync.py | 55 + ...tations_update_workstation_config_async.py | 55 + ...stations_update_workstation_config_sync.py | 55 + ...ed_workstations_update_workstation_sync.py | 55 + .../scripts/fixup_workstations_v1_keywords.py | 195 + .../google-cloud-workstations/v1/setup.py | 91 + .../v1/testing/constraints-3.10.txt | 7 + .../v1/testing/constraints-3.11.txt | 7 + .../v1/testing/constraints-3.12.txt | 7 + .../v1/testing/constraints-3.7.txt | 10 + .../v1/testing/constraints-3.8.txt | 7 + .../v1/testing/constraints-3.9.txt | 7 + .../v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/workstations_v1/__init__.py | 16 + .../workstations_v1/test_workstations.py | 13498 +++++++++++++++ .../v1beta/.coveragerc | 13 + .../google-cloud-workstations/v1beta/.flake8 | 33 + .../v1beta/MANIFEST.in | 2 + .../v1beta/README.rst | 49 + .../v1beta/docs/conf.py | 376 + .../v1beta/docs/index.rst | 7 + .../docs/workstations_v1beta/services.rst | 6 + .../v1beta/docs/workstations_v1beta/types.rst | 6 + .../docs/workstations_v1beta/workstations.rst | 10 + .../google/cloud/workstations/__init__.py | 87 + .../cloud/workstations/gapic_version.py | 16 + .../v1beta/google/cloud/workstations/py.typed | 2 + .../cloud/workstations_v1beta/__init__.py | 88 + .../workstations_v1beta/gapic_metadata.json | 328 + .../workstations_v1beta/gapic_version.py | 16 + .../google/cloud/workstations_v1beta/py.typed | 2 + .../workstations_v1beta/services/__init__.py | 15 + .../services/workstations/__init__.py | 22 + .../services/workstations/async_client.py | 3093 ++++ .../services/workstations/client.py | 3259 ++++ .../services/workstations/pagers.py | 623 + .../workstations/transports/__init__.py | 38 + .../services/workstations/transports/base.py | 545 + .../services/workstations/transports/grpc.py | 943 ++ .../workstations/transports/grpc_asyncio.py | 942 ++ .../services/workstations/transports/rest.py | 3177 ++++ .../workstations_v1beta/types/__init__.py | 80 + .../workstations_v1beta/types/workstations.py | 1793 ++ .../google-cloud-workstations/v1beta/mypy.ini | 3 + .../v1beta/noxfile.py | 184 + ...data_google.cloud.workstations.v1beta.json | 3307 ++++ ...d_workstations_create_workstation_async.py | 57 + ...ations_create_workstation_cluster_async.py | 57 + ...tations_create_workstation_cluster_sync.py | 57 + ...tations_create_workstation_config_async.py | 57 + ...stations_create_workstation_config_sync.py | 57 + ...ed_workstations_create_workstation_sync.py | 57 + ...d_workstations_delete_workstation_async.py | 56 + ...ations_delete_workstation_cluster_async.py | 56 + ...tations_delete_workstation_cluster_sync.py | 56 + ...tations_delete_workstation_config_async.py | 56 + ...stations_delete_workstation_config_sync.py | 56 + ...ed_workstations_delete_workstation_sync.py | 56 + ...orkstations_generate_access_token_async.py | 52 + ...workstations_generate_access_token_sync.py | 52 + ...ated_workstations_get_workstation_async.py | 52 + ...kstations_get_workstation_cluster_async.py | 52 + ...rkstations_get_workstation_cluster_sync.py | 52 + ...rkstations_get_workstation_config_async.py | 52 + ...orkstations_get_workstation_config_sync.py | 52 + ...rated_workstations_get_workstation_sync.py | 52 + ...s_list_usable_workstation_configs_async.py | 53 + ...ns_list_usable_workstation_configs_sync.py | 53 + ...stations_list_usable_workstations_async.py | 53 + ...kstations_list_usable_workstations_sync.py | 53 + ...tations_list_workstation_clusters_async.py | 53 + ...stations_list_workstation_clusters_sync.py | 53 + ...stations_list_workstation_configs_async.py | 53 + ...kstations_list_workstation_configs_sync.py | 53 + ...ed_workstations_list_workstations_async.py | 53 + ...ted_workstations_list_workstations_sync.py | 53 + ...ed_workstations_start_workstation_async.py | 56 + ...ted_workstations_start_workstation_sync.py | 56 + ...ted_workstations_stop_workstation_async.py | 56 + ...ated_workstations_stop_workstation_sync.py | 56 + ...d_workstations_update_workstation_async.py | 55 + ...ations_update_workstation_cluster_async.py | 55 + ...tations_update_workstation_cluster_sync.py | 55 + ...tations_update_workstation_config_async.py | 55 + ...stations_update_workstation_config_sync.py | 55 + ...ed_workstations_update_workstation_sync.py | 55 + .../fixup_workstations_v1beta_keywords.py | 195 + .../google-cloud-workstations/v1beta/setup.py | 91 + .../v1beta/testing/constraints-3.10.txt | 7 + .../v1beta/testing/constraints-3.11.txt | 7 + .../v1beta/testing/constraints-3.12.txt | 7 + .../v1beta/testing/constraints-3.7.txt | 10 + .../v1beta/testing/constraints-3.8.txt | 7 + .../v1beta/testing/constraints-3.9.txt | 7 + .../v1beta/tests/__init__.py | 16 + .../v1beta/tests/unit/__init__.py | 16 + .../v1beta/tests/unit/gapic/__init__.py | 16 + .../gapic/workstations_v1beta/__init__.py | 16 + .../workstations_v1beta/test_workstations.py | 13504 ++++++++++++++++ 168 files changed, 70207 insertions(+) create mode 100644 owl-bot-staging/google-cloud-workstations/v1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-workstations/v1/.flake8 create mode 100644 owl-bot-staging/google-cloud-workstations/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-workstations/v1/README.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/services.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/types.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/workstations.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/py.typed create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/py.typed create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/async_client.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/client.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/pagers.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/base.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/workstations.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-workstations/v1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/scripts/fixup_workstations_v1_keywords.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/setup.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/test_workstations.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/.coveragerc create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/.flake8 create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/README.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/services.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/types.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/workstations.rst create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/py.typed create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/py.typed create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/async_client.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/client.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/pagers.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/base.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/workstations.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/mypy.ini create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/noxfile.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_async.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_sync.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/scripts/fixup_workstations_v1beta_keywords.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/setup.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/__init__.py create mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/test_workstations.py diff --git a/owl-bot-staging/google-cloud-workstations/v1/.coveragerc b/owl-bot-staging/google-cloud-workstations/v1/.coveragerc new file mode 100644 index 000000000000..ee1a17c3e2ca --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/workstations/__init__.py + google/cloud/workstations/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-cloud-workstations/v1/.flake8 b/owl-bot-staging/google-cloud-workstations/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-workstations/v1/MANIFEST.in b/owl-bot-staging/google-cloud-workstations/v1/MANIFEST.in new file mode 100644 index 000000000000..81d49b157276 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/workstations *.py +recursive-include google/cloud/workstations_v1 *.py diff --git a/owl-bot-staging/google-cloud-workstations/v1/README.rst b/owl-bot-staging/google-cloud-workstations/v1/README.rst new file mode 100644 index 000000000000..48a711be018f --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Workstations 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 Workstations API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-workstations/v1/docs/conf.py b/owl-bot-staging/google-cloud-workstations/v1/docs/conf.py new file mode 100644 index 000000000000..06f3a6eac397 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-workstations 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-workstations" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 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-workstations-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-workstations.tex", + u"google-cloud-workstations 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-workstations", + u"Google Cloud Workstations 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-workstations", + u"google-cloud-workstations Documentation", + author, + "google-cloud-workstations", + "GAPIC library for Google Cloud Workstations API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-workstations/v1/docs/index.rst b/owl-bot-staging/google-cloud-workstations/v1/docs/index.rst new file mode 100644 index 000000000000..d037fecd058a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + workstations_v1/services + workstations_v1/types diff --git a/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/services.rst b/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/services.rst new file mode 100644 index 000000000000..4d34f8795a80 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Workstations v1 API +============================================= +.. toctree:: + :maxdepth: 2 + + workstations diff --git a/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/types.rst b/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/types.rst new file mode 100644 index 000000000000..f2d1f8aae76b --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Workstations v1 API +========================================== + +.. automodule:: google.cloud.workstations_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/workstations.rst b/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/workstations.rst new file mode 100644 index 000000000000..1a3ded4d683d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/workstations.rst @@ -0,0 +1,10 @@ +Workstations +------------------------------ + +.. automodule:: google.cloud.workstations_v1.services.workstations + :members: + :inherited-members: + +.. automodule:: google.cloud.workstations_v1.services.workstations.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/__init__.py new file mode 100644 index 000000000000..1528fb82f971 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/__init__.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.workstations import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.workstations_v1.services.workstations.client import WorkstationsClient +from google.cloud.workstations_v1.services.workstations.async_client import WorkstationsAsyncClient + +from google.cloud.workstations_v1.types.workstations import CreateWorkstationClusterRequest +from google.cloud.workstations_v1.types.workstations import CreateWorkstationConfigRequest +from google.cloud.workstations_v1.types.workstations import CreateWorkstationRequest +from google.cloud.workstations_v1.types.workstations import DeleteWorkstationClusterRequest +from google.cloud.workstations_v1.types.workstations import DeleteWorkstationConfigRequest +from google.cloud.workstations_v1.types.workstations import DeleteWorkstationRequest +from google.cloud.workstations_v1.types.workstations import GenerateAccessTokenRequest +from google.cloud.workstations_v1.types.workstations import GenerateAccessTokenResponse +from google.cloud.workstations_v1.types.workstations import GetWorkstationClusterRequest +from google.cloud.workstations_v1.types.workstations import GetWorkstationConfigRequest +from google.cloud.workstations_v1.types.workstations import GetWorkstationRequest +from google.cloud.workstations_v1.types.workstations import ListUsableWorkstationConfigsRequest +from google.cloud.workstations_v1.types.workstations import ListUsableWorkstationConfigsResponse +from google.cloud.workstations_v1.types.workstations import ListUsableWorkstationsRequest +from google.cloud.workstations_v1.types.workstations import ListUsableWorkstationsResponse +from google.cloud.workstations_v1.types.workstations import ListWorkstationClustersRequest +from google.cloud.workstations_v1.types.workstations import ListWorkstationClustersResponse +from google.cloud.workstations_v1.types.workstations import ListWorkstationConfigsRequest +from google.cloud.workstations_v1.types.workstations import ListWorkstationConfigsResponse +from google.cloud.workstations_v1.types.workstations import ListWorkstationsRequest +from google.cloud.workstations_v1.types.workstations import ListWorkstationsResponse +from google.cloud.workstations_v1.types.workstations import OperationMetadata +from google.cloud.workstations_v1.types.workstations import StartWorkstationRequest +from google.cloud.workstations_v1.types.workstations import StopWorkstationRequest +from google.cloud.workstations_v1.types.workstations import UpdateWorkstationClusterRequest +from google.cloud.workstations_v1.types.workstations import UpdateWorkstationConfigRequest +from google.cloud.workstations_v1.types.workstations import UpdateWorkstationRequest +from google.cloud.workstations_v1.types.workstations import Workstation +from google.cloud.workstations_v1.types.workstations import WorkstationCluster +from google.cloud.workstations_v1.types.workstations import WorkstationConfig + +__all__ = ('WorkstationsClient', + 'WorkstationsAsyncClient', + 'CreateWorkstationClusterRequest', + 'CreateWorkstationConfigRequest', + 'CreateWorkstationRequest', + 'DeleteWorkstationClusterRequest', + 'DeleteWorkstationConfigRequest', + 'DeleteWorkstationRequest', + 'GenerateAccessTokenRequest', + 'GenerateAccessTokenResponse', + 'GetWorkstationClusterRequest', + 'GetWorkstationConfigRequest', + 'GetWorkstationRequest', + 'ListUsableWorkstationConfigsRequest', + 'ListUsableWorkstationConfigsResponse', + 'ListUsableWorkstationsRequest', + 'ListUsableWorkstationsResponse', + 'ListWorkstationClustersRequest', + 'ListWorkstationClustersResponse', + 'ListWorkstationConfigsRequest', + 'ListWorkstationConfigsResponse', + 'ListWorkstationsRequest', + 'ListWorkstationsResponse', + 'OperationMetadata', + 'StartWorkstationRequest', + 'StopWorkstationRequest', + 'UpdateWorkstationClusterRequest', + 'UpdateWorkstationConfigRequest', + 'UpdateWorkstationRequest', + 'Workstation', + 'WorkstationCluster', + 'WorkstationConfig', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/gapic_version.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/gapic_version.py new file mode 100644 index 000000000000..360a0d13ebdd --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/py.typed b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/py.typed new file mode 100644 index 000000000000..04170223dff9 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-workstations package uses inline types. diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/__init__.py new file mode 100644 index 000000000000..406625485e84 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/__init__.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.workstations_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.workstations import WorkstationsClient +from .services.workstations import WorkstationsAsyncClient + +from .types.workstations import CreateWorkstationClusterRequest +from .types.workstations import CreateWorkstationConfigRequest +from .types.workstations import CreateWorkstationRequest +from .types.workstations import DeleteWorkstationClusterRequest +from .types.workstations import DeleteWorkstationConfigRequest +from .types.workstations import DeleteWorkstationRequest +from .types.workstations import GenerateAccessTokenRequest +from .types.workstations import GenerateAccessTokenResponse +from .types.workstations import GetWorkstationClusterRequest +from .types.workstations import GetWorkstationConfigRequest +from .types.workstations import GetWorkstationRequest +from .types.workstations import ListUsableWorkstationConfigsRequest +from .types.workstations import ListUsableWorkstationConfigsResponse +from .types.workstations import ListUsableWorkstationsRequest +from .types.workstations import ListUsableWorkstationsResponse +from .types.workstations import ListWorkstationClustersRequest +from .types.workstations import ListWorkstationClustersResponse +from .types.workstations import ListWorkstationConfigsRequest +from .types.workstations import ListWorkstationConfigsResponse +from .types.workstations import ListWorkstationsRequest +from .types.workstations import ListWorkstationsResponse +from .types.workstations import OperationMetadata +from .types.workstations import StartWorkstationRequest +from .types.workstations import StopWorkstationRequest +from .types.workstations import UpdateWorkstationClusterRequest +from .types.workstations import UpdateWorkstationConfigRequest +from .types.workstations import UpdateWorkstationRequest +from .types.workstations import Workstation +from .types.workstations import WorkstationCluster +from .types.workstations import WorkstationConfig + +__all__ = ( + 'WorkstationsAsyncClient', +'CreateWorkstationClusterRequest', +'CreateWorkstationConfigRequest', +'CreateWorkstationRequest', +'DeleteWorkstationClusterRequest', +'DeleteWorkstationConfigRequest', +'DeleteWorkstationRequest', +'GenerateAccessTokenRequest', +'GenerateAccessTokenResponse', +'GetWorkstationClusterRequest', +'GetWorkstationConfigRequest', +'GetWorkstationRequest', +'ListUsableWorkstationConfigsRequest', +'ListUsableWorkstationConfigsResponse', +'ListUsableWorkstationsRequest', +'ListUsableWorkstationsResponse', +'ListWorkstationClustersRequest', +'ListWorkstationClustersResponse', +'ListWorkstationConfigsRequest', +'ListWorkstationConfigsResponse', +'ListWorkstationsRequest', +'ListWorkstationsResponse', +'OperationMetadata', +'StartWorkstationRequest', +'StopWorkstationRequest', +'UpdateWorkstationClusterRequest', +'UpdateWorkstationConfigRequest', +'UpdateWorkstationRequest', +'Workstation', +'WorkstationCluster', +'WorkstationConfig', +'WorkstationsClient', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_metadata.json new file mode 100644 index 000000000000..27a21c6d848b --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_metadata.json @@ -0,0 +1,328 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.workstations_v1", + "protoPackage": "google.cloud.workstations.v1", + "schema": "1.0", + "services": { + "Workstations": { + "clients": { + "grpc": { + "libraryClient": "WorkstationsClient", + "rpcs": { + "CreateWorkstation": { + "methods": [ + "create_workstation" + ] + }, + "CreateWorkstationCluster": { + "methods": [ + "create_workstation_cluster" + ] + }, + "CreateWorkstationConfig": { + "methods": [ + "create_workstation_config" + ] + }, + "DeleteWorkstation": { + "methods": [ + "delete_workstation" + ] + }, + "DeleteWorkstationCluster": { + "methods": [ + "delete_workstation_cluster" + ] + }, + "DeleteWorkstationConfig": { + "methods": [ + "delete_workstation_config" + ] + }, + "GenerateAccessToken": { + "methods": [ + "generate_access_token" + ] + }, + "GetWorkstation": { + "methods": [ + "get_workstation" + ] + }, + "GetWorkstationCluster": { + "methods": [ + "get_workstation_cluster" + ] + }, + "GetWorkstationConfig": { + "methods": [ + "get_workstation_config" + ] + }, + "ListUsableWorkstationConfigs": { + "methods": [ + "list_usable_workstation_configs" + ] + }, + "ListUsableWorkstations": { + "methods": [ + "list_usable_workstations" + ] + }, + "ListWorkstationClusters": { + "methods": [ + "list_workstation_clusters" + ] + }, + "ListWorkstationConfigs": { + "methods": [ + "list_workstation_configs" + ] + }, + "ListWorkstations": { + "methods": [ + "list_workstations" + ] + }, + "StartWorkstation": { + "methods": [ + "start_workstation" + ] + }, + "StopWorkstation": { + "methods": [ + "stop_workstation" + ] + }, + "UpdateWorkstation": { + "methods": [ + "update_workstation" + ] + }, + "UpdateWorkstationCluster": { + "methods": [ + "update_workstation_cluster" + ] + }, + "UpdateWorkstationConfig": { + "methods": [ + "update_workstation_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WorkstationsAsyncClient", + "rpcs": { + "CreateWorkstation": { + "methods": [ + "create_workstation" + ] + }, + "CreateWorkstationCluster": { + "methods": [ + "create_workstation_cluster" + ] + }, + "CreateWorkstationConfig": { + "methods": [ + "create_workstation_config" + ] + }, + "DeleteWorkstation": { + "methods": [ + "delete_workstation" + ] + }, + "DeleteWorkstationCluster": { + "methods": [ + "delete_workstation_cluster" + ] + }, + "DeleteWorkstationConfig": { + "methods": [ + "delete_workstation_config" + ] + }, + "GenerateAccessToken": { + "methods": [ + "generate_access_token" + ] + }, + "GetWorkstation": { + "methods": [ + "get_workstation" + ] + }, + "GetWorkstationCluster": { + "methods": [ + "get_workstation_cluster" + ] + }, + "GetWorkstationConfig": { + "methods": [ + "get_workstation_config" + ] + }, + "ListUsableWorkstationConfigs": { + "methods": [ + "list_usable_workstation_configs" + ] + }, + "ListUsableWorkstations": { + "methods": [ + "list_usable_workstations" + ] + }, + "ListWorkstationClusters": { + "methods": [ + "list_workstation_clusters" + ] + }, + "ListWorkstationConfigs": { + "methods": [ + "list_workstation_configs" + ] + }, + "ListWorkstations": { + "methods": [ + "list_workstations" + ] + }, + "StartWorkstation": { + "methods": [ + "start_workstation" + ] + }, + "StopWorkstation": { + "methods": [ + "stop_workstation" + ] + }, + "UpdateWorkstation": { + "methods": [ + "update_workstation" + ] + }, + "UpdateWorkstationCluster": { + "methods": [ + "update_workstation_cluster" + ] + }, + "UpdateWorkstationConfig": { + "methods": [ + "update_workstation_config" + ] + } + } + }, + "rest": { + "libraryClient": "WorkstationsClient", + "rpcs": { + "CreateWorkstation": { + "methods": [ + "create_workstation" + ] + }, + "CreateWorkstationCluster": { + "methods": [ + "create_workstation_cluster" + ] + }, + "CreateWorkstationConfig": { + "methods": [ + "create_workstation_config" + ] + }, + "DeleteWorkstation": { + "methods": [ + "delete_workstation" + ] + }, + "DeleteWorkstationCluster": { + "methods": [ + "delete_workstation_cluster" + ] + }, + "DeleteWorkstationConfig": { + "methods": [ + "delete_workstation_config" + ] + }, + "GenerateAccessToken": { + "methods": [ + "generate_access_token" + ] + }, + "GetWorkstation": { + "methods": [ + "get_workstation" + ] + }, + "GetWorkstationCluster": { + "methods": [ + "get_workstation_cluster" + ] + }, + "GetWorkstationConfig": { + "methods": [ + "get_workstation_config" + ] + }, + "ListUsableWorkstationConfigs": { + "methods": [ + "list_usable_workstation_configs" + ] + }, + "ListUsableWorkstations": { + "methods": [ + "list_usable_workstations" + ] + }, + "ListWorkstationClusters": { + "methods": [ + "list_workstation_clusters" + ] + }, + "ListWorkstationConfigs": { + "methods": [ + "list_workstation_configs" + ] + }, + "ListWorkstations": { + "methods": [ + "list_workstations" + ] + }, + "StartWorkstation": { + "methods": [ + "start_workstation" + ] + }, + "StopWorkstation": { + "methods": [ + "stop_workstation" + ] + }, + "UpdateWorkstation": { + "methods": [ + "update_workstation" + ] + }, + "UpdateWorkstationCluster": { + "methods": [ + "update_workstation_cluster" + ] + }, + "UpdateWorkstationConfig": { + "methods": [ + "update_workstation_config" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_version.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_version.py new file mode 100644 index 000000000000..360a0d13ebdd --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/py.typed b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/py.typed new file mode 100644 index 000000000000..04170223dff9 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-workstations package uses inline types. diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/__init__.py new file mode 100644 index 000000000000..0d8e475505ba --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 WorkstationsClient +from .async_client import WorkstationsAsyncClient + +__all__ = ( + 'WorkstationsClient', + 'WorkstationsAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/async_client.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/async_client.py new file mode 100644 index 000000000000..2eb4b2d0b046 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/async_client.py @@ -0,0 +1,3093 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.workstations_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1.services.workstations import pagers +from google.cloud.workstations_v1.types import workstations +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 +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import WorkstationsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import WorkstationsGrpcAsyncIOTransport +from .client import WorkstationsClient + + +class WorkstationsAsyncClient: + """Service for interacting with Cloud Workstations.""" + + _client: WorkstationsClient + + DEFAULT_ENDPOINT = WorkstationsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = WorkstationsClient.DEFAULT_MTLS_ENDPOINT + + workstation_path = staticmethod(WorkstationsClient.workstation_path) + parse_workstation_path = staticmethod(WorkstationsClient.parse_workstation_path) + workstation_cluster_path = staticmethod(WorkstationsClient.workstation_cluster_path) + parse_workstation_cluster_path = staticmethod(WorkstationsClient.parse_workstation_cluster_path) + workstation_config_path = staticmethod(WorkstationsClient.workstation_config_path) + parse_workstation_config_path = staticmethod(WorkstationsClient.parse_workstation_config_path) + common_billing_account_path = staticmethod(WorkstationsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(WorkstationsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(WorkstationsClient.common_folder_path) + parse_common_folder_path = staticmethod(WorkstationsClient.parse_common_folder_path) + common_organization_path = staticmethod(WorkstationsClient.common_organization_path) + parse_common_organization_path = staticmethod(WorkstationsClient.parse_common_organization_path) + common_project_path = staticmethod(WorkstationsClient.common_project_path) + parse_common_project_path = staticmethod(WorkstationsClient.parse_common_project_path) + common_location_path = staticmethod(WorkstationsClient.common_location_path) + parse_common_location_path = staticmethod(WorkstationsClient.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: + WorkstationsAsyncClient: The constructed client. + """ + return WorkstationsClient.from_service_account_info.__func__(WorkstationsAsyncClient, 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: + WorkstationsAsyncClient: The constructed client. + """ + return WorkstationsClient.from_service_account_file.__func__(WorkstationsAsyncClient, 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 WorkstationsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> WorkstationsTransport: + """Returns the transport used by the client instance. + + Returns: + WorkstationsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(WorkstationsClient).get_transport_class, type(WorkstationsClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, WorkstationsTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the workstations 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, ~.WorkstationsTransport]): 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 = WorkstationsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_workstation_cluster(self, + request: Optional[Union[workstations.GetWorkstationClusterRequest, 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]] = (), + ) -> workstations.WorkstationCluster: + r"""Returns the requested workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_get_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.GetWorkstationClusterRequest, dict]]): + The request object. Request message for + GetWorkstationCluster. + name (:class:`str`): + Required. Name of the requested + resource. + + 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.workstations_v1.types.WorkstationCluster: + A grouping of workstation + configurations and the associated + workstations in that region. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = workstations.GetWorkstationClusterRequest(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_workstation_cluster, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_workstation_clusters(self, + request: Optional[Union[workstations.ListWorkstationClustersRequest, 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.ListWorkstationClustersAsyncPager: + r"""Returns all workstation clusters in the specified + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_list_workstation_clusters(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.ListWorkstationClustersRequest, dict]]): + The request object. Request message for + ListWorkstationClusters. + parent (:class:`str`): + Required. Parent resource name. + 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.workstations_v1.services.workstations.pagers.ListWorkstationClustersAsyncPager: + Response message for + ListWorkstationClusters. + 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 = workstations.ListWorkstationClustersRequest(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_workstation_clusters, + default_retry=retries.Retry( +initial=1.0,maximum=10.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(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListWorkstationClustersAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_workstation_cluster(self, + request: Optional[Union[workstations.CreateWorkstationClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation_cluster: Optional[workstations.WorkstationCluster] = None, + workstation_cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_create_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationClusterRequest( + parent="parent_value", + workstation_cluster_id="workstation_cluster_id_value", + ) + + # Make the request + operation = client.create_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.CreateWorkstationClusterRequest, dict]]): + The request object. Message for creating a + CreateWorkstationCluster. + parent (:class:`str`): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_cluster (:class:`google.cloud.workstations_v1.types.WorkstationCluster`): + Required. Workstation cluster to + create. + + This corresponds to the ``workstation_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_cluster_id (:class:`str`): + Required. ID to use for the + workstation cluster. + + This corresponds to the ``workstation_cluster_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.workstations_v1.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations + in that region. + + """ + # Create or coerce a protobuf request object. + # Quick 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, workstation_cluster, workstation_cluster_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = workstations.CreateWorkstationClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation_cluster is not None: + request.workstation_cluster = workstation_cluster + if workstation_cluster_id is not None: + request.workstation_cluster_id = workstation_cluster_id + + # 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_workstation_cluster, + 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(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_workstation_cluster(self, + request: Optional[Union[workstations.UpdateWorkstationClusterRequest, dict]] = None, + *, + workstation_cluster: Optional[workstations.WorkstationCluster] = 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 an existing workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_update_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationClusterRequest( + ) + + # Make the request + operation = client.update_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.UpdateWorkstationClusterRequest, dict]]): + The request object. Request message for + UpdateWorkstationCluster. + workstation_cluster (:class:`google.cloud.workstations_v1.types.WorkstationCluster`): + Required. Workstation cluster to + update. + + This corresponds to the ``workstation_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Mask that specifies which + fields in the workstation cluster should + 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.workstations_v1.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations + in that region. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation_cluster, 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 = workstations.UpdateWorkstationClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation_cluster is not None: + request.workstation_cluster = workstation_cluster + 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_workstation_cluster, + 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(( + ("workstation_cluster.name", request.workstation_cluster.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, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_workstation_cluster(self, + request: Optional[Union[workstations.DeleteWorkstationClusterRequest, 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 the specified workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_delete_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.DeleteWorkstationClusterRequest, dict]]): + The request object. Message for deleting a workstation + cluster. + name (:class:`str`): + Required. Name of the workstation + cluster to delete. + + 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.workstations_v1.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations + in that region. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = workstations.DeleteWorkstationClusterRequest(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_workstation_cluster, + 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, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_workstation_config(self, + request: Optional[Union[workstations.GetWorkstationConfigRequest, 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]] = (), + ) -> workstations.WorkstationConfig: + r"""Returns the requested workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_get_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.GetWorkstationConfigRequest, dict]]): + The request object. Request message for + GetWorkstationConfig. + name (:class:`str`): + Required. Name of the requested + resource. + + 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.workstations_v1.types.WorkstationConfig: + A set of configuration options + describing how a workstation will be + run. Workstation configurations are + intended to be shared across multiple + workstations. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = workstations.GetWorkstationConfigRequest(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_workstation_config, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_workstation_configs(self, + request: Optional[Union[workstations.ListWorkstationConfigsRequest, 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.ListWorkstationConfigsAsyncPager: + r"""Returns all workstation configurations in the + specified cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_list_workstation_configs(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.ListWorkstationConfigsRequest, dict]]): + The request object. Request message for + ListWorkstationConfigs. + parent (:class:`str`): + Required. Parent resource name. + 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.workstations_v1.services.workstations.pagers.ListWorkstationConfigsAsyncPager: + Response message for + ListWorkstationConfigs. + 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 = workstations.ListWorkstationConfigsRequest(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_workstation_configs, + default_retry=retries.Retry( +initial=1.0,maximum=10.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(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListWorkstationConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_usable_workstation_configs(self, + request: Optional[Union[workstations.ListUsableWorkstationConfigsRequest, 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.ListUsableWorkstationConfigsAsyncPager: + r"""Returns all workstation configurations in the + specified cluster on which the caller has the + "workstations.workstation.create" permission. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_list_usable_workstation_configs(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListUsableWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstation_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest, dict]]): + The request object. Request message for + ListUsableWorkstationConfigs. + parent (:class:`str`): + Required. Parent resource name. + 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.workstations_v1.services.workstations.pagers.ListUsableWorkstationConfigsAsyncPager: + Response message for + ListUsableWorkstationConfigs. + 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 = workstations.ListUsableWorkstationConfigsRequest(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_usable_workstation_configs, + default_retry=retries.Retry( +initial=1.0,maximum=10.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(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListUsableWorkstationConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_workstation_config(self, + request: Optional[Union[workstations.CreateWorkstationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation_config: Optional[workstations.WorkstationConfig] = None, + workstation_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_create_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationConfigRequest( + parent="parent_value", + workstation_config_id="workstation_config_id_value", + ) + + # Make the request + operation = client.create_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.CreateWorkstationConfigRequest, dict]]): + The request object. Message for creating a + CreateWorkstationConfig. + parent (:class:`str`): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_config (:class:`google.cloud.workstations_v1.types.WorkstationConfig`): + Required. Config to create. + This corresponds to the ``workstation_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_config_id (:class:`str`): + Required. ID to use for the + workstation configuration. + + This corresponds to the ``workstation_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.workstations_v1.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. + Workstation configurations are intended to be shared + across multiple workstations. + + """ + # Create or coerce a protobuf request object. + # Quick 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, workstation_config, workstation_config_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = workstations.CreateWorkstationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation_config is not None: + request.workstation_config = workstation_config + if workstation_config_id is not None: + request.workstation_config_id = workstation_config_id + + # 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_workstation_config, + 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(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_workstation_config(self, + request: Optional[Union[workstations.UpdateWorkstationConfigRequest, dict]] = None, + *, + workstation_config: Optional[workstations.WorkstationConfig] = 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 an existing workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_update_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationConfigRequest( + ) + + # Make the request + operation = client.update_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.UpdateWorkstationConfigRequest, dict]]): + The request object. Request message for + UpdateWorkstationConfig. + workstation_config (:class:`google.cloud.workstations_v1.types.WorkstationConfig`): + Required. Config to update. + This corresponds to the ``workstation_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Mask specifying which + fields in the workstation configuration + should 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.workstations_v1.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. + Workstation configurations are intended to be shared + across multiple workstations. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = workstations.UpdateWorkstationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation_config is not None: + request.workstation_config = workstation_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_workstation_config, + 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(( + ("workstation_config.name", request.workstation_config.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, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_workstation_config(self, + request: Optional[Union[workstations.DeleteWorkstationConfigRequest, 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 the specified workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_delete_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.DeleteWorkstationConfigRequest, dict]]): + The request object. Message for deleting a workstation + configuration. + name (:class:`str`): + Required. Name of the workstation + configuration to delete. + + 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.workstations_v1.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. + Workstation configurations are intended to be shared + across multiple workstations. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = workstations.DeleteWorkstationConfigRequest(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_workstation_config, + 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, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_workstation(self, + request: Optional[Union[workstations.GetWorkstationRequest, 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]] = (), + ) -> workstations.Workstation: + r"""Returns the requested workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_get_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.GetWorkstationRequest, dict]]): + The request object. Request message for GetWorkstation. + name (:class:`str`): + Required. Name of the requested + resource. + + 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.workstations_v1.types.Workstation: + A single instance of a developer + workstation with its own persistent + storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = workstations.GetWorkstationRequest(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_workstation, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_workstations(self, + request: Optional[Union[workstations.ListWorkstationsRequest, 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.ListWorkstationsAsyncPager: + r"""Returns all Workstations using the specified + workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_list_workstations(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.ListWorkstationsRequest, dict]]): + The request object. Request message for ListWorkstations. + parent (:class:`str`): + Required. Parent resource name. + 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.workstations_v1.services.workstations.pagers.ListWorkstationsAsyncPager: + Response message for + ListWorkstations. + 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 = workstations.ListWorkstationsRequest(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_workstations, + default_retry=retries.Retry( +initial=1.0,maximum=10.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(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListWorkstationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_usable_workstations(self, + request: Optional[Union[workstations.ListUsableWorkstationsRequest, 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.ListUsableWorkstationsAsyncPager: + r"""Returns all workstations using the specified + workstation configuration on which the caller has the + "workstations.workstations.use" permission. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_list_usable_workstations(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListUsableWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.ListUsableWorkstationsRequest, dict]]): + The request object. Request message for + ListUsableWorkstations. + parent (:class:`str`): + Required. Parent resource name. + 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.workstations_v1.services.workstations.pagers.ListUsableWorkstationsAsyncPager: + Response message for + ListUsableWorkstations. + 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 = workstations.ListUsableWorkstationsRequest(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_usable_workstations, + default_retry=retries.Retry( +initial=1.0,maximum=10.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(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListUsableWorkstationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_workstation(self, + request: Optional[Union[workstations.CreateWorkstationRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation: Optional[workstations.Workstation] = None, + workstation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_create_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationRequest( + parent="parent_value", + workstation_id="workstation_id_value", + ) + + # Make the request + operation = client.create_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.CreateWorkstationRequest, dict]]): + The request object. Message for creating a + CreateWorkstation. + parent (:class:`str`): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation (:class:`google.cloud.workstations_v1.types.Workstation`): + Required. Workstation to create. + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_id (:class:`str`): + Required. ID to use for the + workstation. + + This corresponds to the ``workstation_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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, workstation, workstation_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = workstations.CreateWorkstationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation is not None: + request.workstation = workstation + if workstation_id is not None: + request.workstation_id = workstation_id + + # 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_workstation, + 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(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_workstation(self, + request: Optional[Union[workstations.UpdateWorkstationRequest, dict]] = None, + *, + workstation: Optional[workstations.Workstation] = 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 an existing workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_update_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationRequest( + ) + + # Make the request + operation = client.update_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.UpdateWorkstationRequest, dict]]): + The request object. Request message for + UpdateWorkstation. + workstation (:class:`google.cloud.workstations_v1.types.Workstation`): + Required. Workstation to update. + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Mask specifying which + fields in the workstation configuration + should 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.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation, 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 = workstations.UpdateWorkstationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation is not None: + request.workstation = workstation + 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_workstation, + 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(( + ("workstation.name", request.workstation.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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_workstation(self, + request: Optional[Union[workstations.DeleteWorkstationRequest, 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 the specified workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_delete_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.DeleteWorkstationRequest, dict]]): + The request object. Request message for + DeleteWorkstation. + name (:class:`str`): + Required. Name of the workstation to + delete. + + 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.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = workstations.DeleteWorkstationRequest(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_workstation, + 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def start_workstation(self, + request: Optional[Union[workstations.StartWorkstationRequest, 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"""Starts running a workstation so that users can + connect to 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 workstations_v1 + + async def sample_start_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.StartWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.start_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.StartWorkstationRequest, dict]]): + The request object. Request message for StartWorkstation. + name (:class:`str`): + Required. Name of the workstation to + start. + + 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.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = workstations.StartWorkstationRequest(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.start_workstation, + 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def stop_workstation(self, + request: Optional[Union[workstations.StopWorkstationRequest, 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"""Stops running a workstation, reducing costs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_stop_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.StopWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.StopWorkstationRequest, dict]]): + The request object. Request message for StopWorkstation. + name (:class:`str`): + Required. Name of the workstation to + stop. + + 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.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = workstations.StopWorkstationRequest(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.stop_workstation, + 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def generate_access_token(self, + request: Optional[Union[workstations.GenerateAccessTokenRequest, dict]] = None, + *, + workstation: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.GenerateAccessTokenResponse: + r"""Returns a short-lived credential that can be used to + send authenticated and authorized traffic to a + workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + async def sample_generate_access_token(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.GenerateAccessTokenRequest( + workstation="workstation_value", + ) + + # Make the request + response = await client.generate_access_token(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1.types.GenerateAccessTokenRequest, dict]]): + The request object. Request message for + GenerateAccessToken. + workstation (:class:`str`): + Required. Name of the workstation for + which the access token should be + generated. + + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1.types.GenerateAccessTokenResponse: + Response message for + GenerateAccessToken. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation]) + if request is 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 = workstations.GenerateAccessTokenRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation is not None: + request.workstation = workstation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.generate_access_token, + default_retry=retries.Retry( +initial=1.0,maximum=10.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(( + ("workstation", request.workstation), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._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) -> "WorkstationsAsyncClient": + 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__ = ( + "WorkstationsAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/client.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/client.py new file mode 100644 index 000000000000..746805281c7b --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/client.py @@ -0,0 +1,3259 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.workstations_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1.services.workstations import pagers +from google.cloud.workstations_v1.types import workstations +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 +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import WorkstationsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import WorkstationsGrpcTransport +from .transports.grpc_asyncio import WorkstationsGrpcAsyncIOTransport +from .transports.rest import WorkstationsRestTransport + + +class WorkstationsClientMeta(type): + """Metaclass for the Workstations 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[WorkstationsTransport]] + _transport_registry["grpc"] = WorkstationsGrpcTransport + _transport_registry["grpc_asyncio"] = WorkstationsGrpcAsyncIOTransport + _transport_registry["rest"] = WorkstationsRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[WorkstationsTransport]: + """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 WorkstationsClient(metaclass=WorkstationsClientMeta): + """Service for interacting with Cloud Workstations.""" + + @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 = "workstations.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: + WorkstationsClient: 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: + WorkstationsClient: 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) -> WorkstationsTransport: + """Returns the transport used by the client instance. + + Returns: + WorkstationsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def workstation_path(project: str,location: str,workstation_cluster: str,workstation_config: str,workstation: str,) -> str: + """Returns a fully-qualified workstation string.""" + return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}/workstations/{workstation}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, workstation=workstation, ) + + @staticmethod + def parse_workstation_path(path: str) -> Dict[str,str]: + """Parses a workstation path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)/workstationConfigs/(?P.+?)/workstations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def workstation_cluster_path(project: str,location: str,workstation_cluster: str,) -> str: + """Returns a fully-qualified workstation_cluster string.""" + return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}".format(project=project, location=location, workstation_cluster=workstation_cluster, ) + + @staticmethod + def parse_workstation_cluster_path(path: str) -> Dict[str,str]: + """Parses a workstation_cluster path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def workstation_config_path(project: str,location: str,workstation_cluster: str,workstation_config: str,) -> str: + """Returns a fully-qualified workstation_config string.""" + return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, ) + + @staticmethod + def parse_workstation_config_path(path: str) -> Dict[str,str]: + """Parses a workstation_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)/workstationConfigs/(?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, WorkstationsTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the workstations 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, WorkstationsTransport]): 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, WorkstationsTransport): + # transport is a WorkstationsTransport 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_workstation_cluster(self, + request: Optional[Union[workstations.GetWorkstationClusterRequest, 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]] = (), + ) -> workstations.WorkstationCluster: + r"""Returns the requested workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_get_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.GetWorkstationClusterRequest, dict]): + The request object. Request message for + GetWorkstationCluster. + name (str): + Required. Name of the requested + resource. + + 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.workstations_v1.types.WorkstationCluster: + A grouping of workstation + configurations and the associated + workstations in that region. + + """ + # Create or coerce a protobuf request object. + # Quick 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 workstations.GetWorkstationClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.GetWorkstationClusterRequest): + request = workstations.GetWorkstationClusterRequest(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_workstation_cluster] + + # Certain 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_workstation_clusters(self, + request: Optional[Union[workstations.ListWorkstationClustersRequest, 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.ListWorkstationClustersPager: + r"""Returns all workstation clusters in the specified + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_list_workstation_clusters(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.ListWorkstationClustersRequest, dict]): + The request object. Request message for + ListWorkstationClusters. + parent (str): + Required. Parent resource name. + 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.workstations_v1.services.workstations.pagers.ListWorkstationClustersPager: + Response message for + ListWorkstationClusters. + 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 workstations.ListWorkstationClustersRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.ListWorkstationClustersRequest): + request = workstations.ListWorkstationClustersRequest(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_workstation_clusters] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListWorkstationClustersPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_workstation_cluster(self, + request: Optional[Union[workstations.CreateWorkstationClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation_cluster: Optional[workstations.WorkstationCluster] = None, + workstation_cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_create_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationClusterRequest( + parent="parent_value", + workstation_cluster_id="workstation_cluster_id_value", + ) + + # Make the request + operation = client.create_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.CreateWorkstationClusterRequest, dict]): + The request object. Message for creating a + CreateWorkstationCluster. + parent (str): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_cluster (google.cloud.workstations_v1.types.WorkstationCluster): + Required. Workstation cluster to + create. + + This corresponds to the ``workstation_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_cluster_id (str): + Required. ID to use for the + workstation cluster. + + This corresponds to the ``workstation_cluster_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.workstations_v1.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations + in that region. + + """ + # Create or coerce a protobuf request object. + # Quick 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, workstation_cluster, workstation_cluster_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a workstations.CreateWorkstationClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.CreateWorkstationClusterRequest): + request = workstations.CreateWorkstationClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation_cluster is not None: + request.workstation_cluster = workstation_cluster + if workstation_cluster_id is not None: + request.workstation_cluster_id = workstation_cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_workstation_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_workstation_cluster(self, + request: Optional[Union[workstations.UpdateWorkstationClusterRequest, dict]] = None, + *, + workstation_cluster: Optional[workstations.WorkstationCluster] = 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 an existing workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_update_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationClusterRequest( + ) + + # Make the request + operation = client.update_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.UpdateWorkstationClusterRequest, dict]): + The request object. Request message for + UpdateWorkstationCluster. + workstation_cluster (google.cloud.workstations_v1.types.WorkstationCluster): + Required. Workstation cluster to + update. + + This corresponds to the ``workstation_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask that specifies which + fields in the workstation cluster should + 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.workstations_v1.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations + in that region. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation_cluster, 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 workstations.UpdateWorkstationClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.UpdateWorkstationClusterRequest): + request = workstations.UpdateWorkstationClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation_cluster is not None: + request.workstation_cluster = workstation_cluster + 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_workstation_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation_cluster.name", request.workstation_cluster.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, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_workstation_cluster(self, + request: Optional[Union[workstations.DeleteWorkstationClusterRequest, 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 the specified workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_delete_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.DeleteWorkstationClusterRequest, dict]): + The request object. Message for deleting a workstation + cluster. + name (str): + Required. Name of the workstation + cluster to delete. + + 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.workstations_v1.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations + in that region. + + """ + # Create or coerce a protobuf request object. + # Quick 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 workstations.DeleteWorkstationClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.DeleteWorkstationClusterRequest): + request = workstations.DeleteWorkstationClusterRequest(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_workstation_cluster] + + # Certain 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, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_workstation_config(self, + request: Optional[Union[workstations.GetWorkstationConfigRequest, 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]] = (), + ) -> workstations.WorkstationConfig: + r"""Returns the requested workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_get_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.GetWorkstationConfigRequest, dict]): + The request object. Request message for + GetWorkstationConfig. + name (str): + Required. Name of the requested + resource. + + 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.workstations_v1.types.WorkstationConfig: + A set of configuration options + describing how a workstation will be + run. Workstation configurations are + intended to be shared across multiple + workstations. + + """ + # Create or coerce a protobuf request object. + # Quick 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 workstations.GetWorkstationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.GetWorkstationConfigRequest): + request = workstations.GetWorkstationConfigRequest(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_workstation_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_workstation_configs(self, + request: Optional[Union[workstations.ListWorkstationConfigsRequest, 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.ListWorkstationConfigsPager: + r"""Returns all workstation configurations in the + specified cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_list_workstation_configs(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.ListWorkstationConfigsRequest, dict]): + The request object. Request message for + ListWorkstationConfigs. + parent (str): + Required. Parent resource name. + 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.workstations_v1.services.workstations.pagers.ListWorkstationConfigsPager: + Response message for + ListWorkstationConfigs. + 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 workstations.ListWorkstationConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.ListWorkstationConfigsRequest): + request = workstations.ListWorkstationConfigsRequest(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_workstation_configs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListWorkstationConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_usable_workstation_configs(self, + request: Optional[Union[workstations.ListUsableWorkstationConfigsRequest, 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.ListUsableWorkstationConfigsPager: + r"""Returns all workstation configurations in the + specified cluster on which the caller has the + "workstations.workstation.create" permission. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_list_usable_workstation_configs(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListUsableWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstation_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest, dict]): + The request object. Request message for + ListUsableWorkstationConfigs. + parent (str): + Required. Parent resource name. + 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.workstations_v1.services.workstations.pagers.ListUsableWorkstationConfigsPager: + Response message for + ListUsableWorkstationConfigs. + 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 workstations.ListUsableWorkstationConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.ListUsableWorkstationConfigsRequest): + request = workstations.ListUsableWorkstationConfigsRequest(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_usable_workstation_configs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListUsableWorkstationConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_workstation_config(self, + request: Optional[Union[workstations.CreateWorkstationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation_config: Optional[workstations.WorkstationConfig] = None, + workstation_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_create_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationConfigRequest( + parent="parent_value", + workstation_config_id="workstation_config_id_value", + ) + + # Make the request + operation = client.create_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.CreateWorkstationConfigRequest, dict]): + The request object. Message for creating a + CreateWorkstationConfig. + parent (str): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_config (google.cloud.workstations_v1.types.WorkstationConfig): + Required. Config to create. + This corresponds to the ``workstation_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_config_id (str): + Required. ID to use for the + workstation configuration. + + This corresponds to the ``workstation_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.workstations_v1.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. + Workstation configurations are intended to be shared + across multiple workstations. + + """ + # Create or coerce a protobuf request object. + # Quick 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, workstation_config, workstation_config_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a workstations.CreateWorkstationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.CreateWorkstationConfigRequest): + request = workstations.CreateWorkstationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation_config is not None: + request.workstation_config = workstation_config + if workstation_config_id is not None: + request.workstation_config_id = workstation_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_workstation_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # 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, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_workstation_config(self, + request: Optional[Union[workstations.UpdateWorkstationConfigRequest, dict]] = None, + *, + workstation_config: Optional[workstations.WorkstationConfig] = 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 an existing workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_update_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationConfigRequest( + ) + + # Make the request + operation = client.update_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.UpdateWorkstationConfigRequest, dict]): + The request object. Request message for + UpdateWorkstationConfig. + workstation_config (google.cloud.workstations_v1.types.WorkstationConfig): + Required. Config to update. + This corresponds to the ``workstation_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask specifying which + fields in the workstation configuration + should 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.workstations_v1.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. + Workstation configurations are intended to be shared + across multiple workstations. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a workstations.UpdateWorkstationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.UpdateWorkstationConfigRequest): + request = workstations.UpdateWorkstationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation_config is not None: + request.workstation_config = workstation_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_workstation_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation_config.name", request.workstation_config.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, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_workstation_config(self, + request: Optional[Union[workstations.DeleteWorkstationConfigRequest, 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 the specified workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_delete_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.DeleteWorkstationConfigRequest, dict]): + The request object. Message for deleting a workstation + configuration. + name (str): + Required. Name of the workstation + configuration to delete. + + 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.workstations_v1.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. + Workstation configurations are intended to be shared + across multiple workstations. + + """ + # Create or coerce a protobuf request object. + # Quick 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 workstations.DeleteWorkstationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.DeleteWorkstationConfigRequest): + request = workstations.DeleteWorkstationConfigRequest(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_workstation_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # 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, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_workstation(self, + request: Optional[Union[workstations.GetWorkstationRequest, 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]] = (), + ) -> workstations.Workstation: + r"""Returns the requested workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_get_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.GetWorkstationRequest, dict]): + The request object. Request message for GetWorkstation. + name (str): + Required. Name of the requested + resource. + + 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.workstations_v1.types.Workstation: + A single instance of a developer + workstation with its own persistent + storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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 workstations.GetWorkstationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.GetWorkstationRequest): + request = workstations.GetWorkstationRequest(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_workstation] + + # Certain 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_workstations(self, + request: Optional[Union[workstations.ListWorkstationsRequest, 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.ListWorkstationsPager: + r"""Returns all Workstations using the specified + workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_list_workstations(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.ListWorkstationsRequest, dict]): + The request object. Request message for ListWorkstations. + parent (str): + Required. Parent resource name. + 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.workstations_v1.services.workstations.pagers.ListWorkstationsPager: + Response message for + ListWorkstations. + 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 workstations.ListWorkstationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.ListWorkstationsRequest): + request = workstations.ListWorkstationsRequest(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_workstations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListWorkstationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_usable_workstations(self, + request: Optional[Union[workstations.ListUsableWorkstationsRequest, 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.ListUsableWorkstationsPager: + r"""Returns all workstations using the specified + workstation configuration on which the caller has the + "workstations.workstations.use" permission. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_list_usable_workstations(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListUsableWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.ListUsableWorkstationsRequest, dict]): + The request object. Request message for + ListUsableWorkstations. + parent (str): + Required. Parent resource name. + 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.workstations_v1.services.workstations.pagers.ListUsableWorkstationsPager: + Response message for + ListUsableWorkstations. + 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 workstations.ListUsableWorkstationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.ListUsableWorkstationsRequest): + request = workstations.ListUsableWorkstationsRequest(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_usable_workstations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListUsableWorkstationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_workstation(self, + request: Optional[Union[workstations.CreateWorkstationRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation: Optional[workstations.Workstation] = None, + workstation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_create_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationRequest( + parent="parent_value", + workstation_id="workstation_id_value", + ) + + # Make the request + operation = client.create_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.CreateWorkstationRequest, dict]): + The request object. Message for creating a + CreateWorkstation. + parent (str): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation (google.cloud.workstations_v1.types.Workstation): + Required. Workstation to create. + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_id (str): + Required. ID to use for the + workstation. + + This corresponds to the ``workstation_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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, workstation, workstation_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a workstations.CreateWorkstationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.CreateWorkstationRequest): + request = workstations.CreateWorkstationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation is not None: + request.workstation = workstation + if workstation_id is not None: + request.workstation_id = workstation_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_workstation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_workstation(self, + request: Optional[Union[workstations.UpdateWorkstationRequest, dict]] = None, + *, + workstation: Optional[workstations.Workstation] = 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 an existing workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_update_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationRequest( + ) + + # Make the request + operation = client.update_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.UpdateWorkstationRequest, dict]): + The request object. Request message for + UpdateWorkstation. + workstation (google.cloud.workstations_v1.types.Workstation): + Required. Workstation to update. + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask specifying which + fields in the workstation configuration + should 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.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation, 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 workstations.UpdateWorkstationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.UpdateWorkstationRequest): + request = workstations.UpdateWorkstationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation is not None: + request.workstation = workstation + 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_workstation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation.name", request.workstation.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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_workstation(self, + request: Optional[Union[workstations.DeleteWorkstationRequest, 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 the specified workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_delete_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.DeleteWorkstationRequest, dict]): + The request object. Request message for + DeleteWorkstation. + name (str): + Required. Name of the workstation to + delete. + + 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.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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 workstations.DeleteWorkstationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.DeleteWorkstationRequest): + request = workstations.DeleteWorkstationRequest(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_workstation] + + # Certain 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def start_workstation(self, + request: Optional[Union[workstations.StartWorkstationRequest, 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"""Starts running a workstation so that users can + connect to 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 workstations_v1 + + def sample_start_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.StartWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.start_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.StartWorkstationRequest, dict]): + The request object. Request message for StartWorkstation. + name (str): + Required. Name of the workstation to + start. + + 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.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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 workstations.StartWorkstationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.StartWorkstationRequest): + request = workstations.StartWorkstationRequest(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.start_workstation] + + # Certain 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def stop_workstation(self, + request: Optional[Union[workstations.StopWorkstationRequest, 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"""Stops running a workstation, reducing costs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_stop_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.StopWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.StopWorkstationRequest, dict]): + The request object. Request message for StopWorkstation. + name (str): + Required. Name of the workstation to + stop. + + 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.workstations_v1.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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 workstations.StopWorkstationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.StopWorkstationRequest): + request = workstations.StopWorkstationRequest(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.stop_workstation] + + # Certain 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def generate_access_token(self, + request: Optional[Union[workstations.GenerateAccessTokenRequest, dict]] = None, + *, + workstation: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.GenerateAccessTokenResponse: + r"""Returns a short-lived credential that can be used to + send authenticated and authorized traffic to a + workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1 + + def sample_generate_access_token(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.GenerateAccessTokenRequest( + workstation="workstation_value", + ) + + # Make the request + response = client.generate_access_token(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1.types.GenerateAccessTokenRequest, dict]): + The request object. Request message for + GenerateAccessToken. + workstation (str): + Required. Name of the workstation for + which the access token should be + generated. + + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1.types.GenerateAccessTokenResponse: + Response message for + GenerateAccessToken. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation]) + if request is 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 workstations.GenerateAccessTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.GenerateAccessTokenRequest): + request = workstations.GenerateAccessTokenRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation is not None: + request.workstation = workstation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_access_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation", request.workstation), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "WorkstationsClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "WorkstationsClient", +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/pagers.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/pagers.py new file mode 100644 index 000000000000..1d2bafb58129 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/pagers.py @@ -0,0 +1,623 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.workstations_v1.types import workstations + + +class ListWorkstationClustersPager: + """A pager for iterating through ``list_workstation_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListWorkstationClustersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstation_clusters`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWorkstationClusters`` requests and continue to iterate + through the ``workstation_clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationClustersResponse` + 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[..., workstations.ListWorkstationClustersResponse], + request: workstations.ListWorkstationClustersRequest, + response: workstations.ListWorkstationClustersResponse, + *, + 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.workstations_v1.types.ListWorkstationClustersRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListWorkstationClustersResponse): + 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 = workstations.ListWorkstationClustersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[workstations.ListWorkstationClustersResponse]: + 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[workstations.WorkstationCluster]: + for page in self.pages: + yield from page.workstation_clusters + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationClustersAsyncPager: + """A pager for iterating through ``list_workstation_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListWorkstationClustersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstation_clusters`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWorkstationClusters`` requests and continue to iterate + through the ``workstation_clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationClustersResponse` + 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[workstations.ListWorkstationClustersResponse]], + request: workstations.ListWorkstationClustersRequest, + response: workstations.ListWorkstationClustersResponse, + *, + 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.workstations_v1.types.ListWorkstationClustersRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListWorkstationClustersResponse): + 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 = workstations.ListWorkstationClustersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[workstations.ListWorkstationClustersResponse]: + 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[workstations.WorkstationCluster]: + async def async_generator(): + async for page in self.pages: + for response in page.workstation_clusters: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationConfigsPager: + """A pager for iterating through ``list_workstation_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListWorkstationConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstation_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWorkstationConfigs`` requests and continue to iterate + through the ``workstation_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationConfigsResponse` + 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[..., workstations.ListWorkstationConfigsResponse], + request: workstations.ListWorkstationConfigsRequest, + response: workstations.ListWorkstationConfigsResponse, + *, + 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.workstations_v1.types.ListWorkstationConfigsRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListWorkstationConfigsResponse): + 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 = workstations.ListWorkstationConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[workstations.ListWorkstationConfigsResponse]: + 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[workstations.WorkstationConfig]: + for page in self.pages: + yield from page.workstation_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationConfigsAsyncPager: + """A pager for iterating through ``list_workstation_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListWorkstationConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstation_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWorkstationConfigs`` requests and continue to iterate + through the ``workstation_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationConfigsResponse` + 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[workstations.ListWorkstationConfigsResponse]], + request: workstations.ListWorkstationConfigsRequest, + response: workstations.ListWorkstationConfigsResponse, + *, + 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.workstations_v1.types.ListWorkstationConfigsRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListWorkstationConfigsResponse): + 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 = workstations.ListWorkstationConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[workstations.ListWorkstationConfigsResponse]: + 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[workstations.WorkstationConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.workstation_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsableWorkstationConfigsPager: + """A pager for iterating through ``list_usable_workstation_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstation_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUsableWorkstationConfigs`` requests and continue to iterate + through the ``workstation_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse` + 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[..., workstations.ListUsableWorkstationConfigsResponse], + request: workstations.ListUsableWorkstationConfigsRequest, + response: workstations.ListUsableWorkstationConfigsResponse, + *, + 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.workstations_v1.types.ListUsableWorkstationConfigsRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse): + 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 = workstations.ListUsableWorkstationConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[workstations.ListUsableWorkstationConfigsResponse]: + 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[workstations.WorkstationConfig]: + for page in self.pages: + yield from page.workstation_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsableWorkstationConfigsAsyncPager: + """A pager for iterating through ``list_usable_workstation_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstation_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUsableWorkstationConfigs`` requests and continue to iterate + through the ``workstation_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse` + 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[workstations.ListUsableWorkstationConfigsResponse]], + request: workstations.ListUsableWorkstationConfigsRequest, + response: workstations.ListUsableWorkstationConfigsResponse, + *, + 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.workstations_v1.types.ListUsableWorkstationConfigsRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse): + 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 = workstations.ListUsableWorkstationConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[workstations.ListUsableWorkstationConfigsResponse]: + 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[workstations.WorkstationConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.workstation_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationsPager: + """A pager for iterating through ``list_workstations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListWorkstationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWorkstations`` requests and continue to iterate + through the ``workstations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationsResponse` + 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[..., workstations.ListWorkstationsResponse], + request: workstations.ListWorkstationsRequest, + response: workstations.ListWorkstationsResponse, + *, + 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.workstations_v1.types.ListWorkstationsRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListWorkstationsResponse): + 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 = workstations.ListWorkstationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[workstations.ListWorkstationsResponse]: + 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[workstations.Workstation]: + for page in self.pages: + yield from page.workstations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationsAsyncPager: + """A pager for iterating through ``list_workstations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListWorkstationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWorkstations`` requests and continue to iterate + through the ``workstations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationsResponse` + 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[workstations.ListWorkstationsResponse]], + request: workstations.ListWorkstationsRequest, + response: workstations.ListWorkstationsResponse, + *, + 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.workstations_v1.types.ListWorkstationsRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListWorkstationsResponse): + 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 = workstations.ListWorkstationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[workstations.ListWorkstationsResponse]: + 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[workstations.Workstation]: + async def async_generator(): + async for page in self.pages: + for response in page.workstations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsableWorkstationsPager: + """A pager for iterating through ``list_usable_workstations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListUsableWorkstationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUsableWorkstations`` requests and continue to iterate + through the ``workstations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListUsableWorkstationsResponse` + 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[..., workstations.ListUsableWorkstationsResponse], + request: workstations.ListUsableWorkstationsRequest, + response: workstations.ListUsableWorkstationsResponse, + *, + 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.workstations_v1.types.ListUsableWorkstationsRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListUsableWorkstationsResponse): + 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 = workstations.ListUsableWorkstationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[workstations.ListUsableWorkstationsResponse]: + 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[workstations.Workstation]: + for page in self.pages: + yield from page.workstations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsableWorkstationsAsyncPager: + """A pager for iterating through ``list_usable_workstations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1.types.ListUsableWorkstationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUsableWorkstations`` requests and continue to iterate + through the ``workstations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1.types.ListUsableWorkstationsResponse` + 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[workstations.ListUsableWorkstationsResponse]], + request: workstations.ListUsableWorkstationsRequest, + response: workstations.ListUsableWorkstationsResponse, + *, + 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.workstations_v1.types.ListUsableWorkstationsRequest): + The initial request object. + response (google.cloud.workstations_v1.types.ListUsableWorkstationsResponse): + 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 = workstations.ListUsableWorkstationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[workstations.ListUsableWorkstationsResponse]: + 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[workstations.Workstation]: + async def async_generator(): + async for page in self.pages: + for response in page.workstations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/__init__.py new file mode 100644 index 000000000000..fc931d51cd5e --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 WorkstationsTransport +from .grpc import WorkstationsGrpcTransport +from .grpc_asyncio import WorkstationsGrpcAsyncIOTransport +from .rest import WorkstationsRestTransport +from .rest import WorkstationsRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[WorkstationsTransport]] +_transport_registry['grpc'] = WorkstationsGrpcTransport +_transport_registry['grpc_asyncio'] = WorkstationsGrpcAsyncIOTransport +_transport_registry['rest'] = WorkstationsRestTransport + +__all__ = ( + 'WorkstationsTransport', + 'WorkstationsGrpcTransport', + 'WorkstationsGrpcAsyncIOTransport', + 'WorkstationsRestTransport', + 'WorkstationsRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/base.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/base.py new file mode 100644 index 000000000000..0a8e7d09a29d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/base.py @@ -0,0 +1,545 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.workstations_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1.types import workstations +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 +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class WorkstationsTransport(abc.ABC): + """Abstract transport class for Workstations.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'workstations.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_workstation_cluster: gapic_v1.method.wrap_method( + self.get_workstation_cluster, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_workstation_clusters: gapic_v1.method.wrap_method( + self.list_workstation_clusters, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_workstation_cluster: gapic_v1.method.wrap_method( + self.create_workstation_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.update_workstation_cluster: gapic_v1.method.wrap_method( + self.update_workstation_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_workstation_cluster: gapic_v1.method.wrap_method( + self.delete_workstation_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.get_workstation_config: gapic_v1.method.wrap_method( + self.get_workstation_config, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_workstation_configs: gapic_v1.method.wrap_method( + self.list_workstation_configs, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_usable_workstation_configs: gapic_v1.method.wrap_method( + self.list_usable_workstation_configs, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_workstation_config: gapic_v1.method.wrap_method( + self.create_workstation_config, + default_timeout=60.0, + client_info=client_info, + ), + self.update_workstation_config: gapic_v1.method.wrap_method( + self.update_workstation_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_workstation_config: gapic_v1.method.wrap_method( + self.delete_workstation_config, + default_timeout=60.0, + client_info=client_info, + ), + self.get_workstation: gapic_v1.method.wrap_method( + self.get_workstation, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_workstations: gapic_v1.method.wrap_method( + self.list_workstations, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_usable_workstations: gapic_v1.method.wrap_method( + self.list_usable_workstations, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_workstation: gapic_v1.method.wrap_method( + self.create_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.update_workstation: gapic_v1.method.wrap_method( + self.update_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_workstation: gapic_v1.method.wrap_method( + self.delete_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.start_workstation: gapic_v1.method.wrap_method( + self.start_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.stop_workstation: gapic_v1.method.wrap_method( + self.stop_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.generate_access_token: gapic_v1.method.wrap_method( + self.generate_access_token, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + 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 get_workstation_cluster(self) -> Callable[ + [workstations.GetWorkstationClusterRequest], + Union[ + workstations.WorkstationCluster, + Awaitable[workstations.WorkstationCluster] + ]]: + raise NotImplementedError() + + @property + def list_workstation_clusters(self) -> Callable[ + [workstations.ListWorkstationClustersRequest], + Union[ + workstations.ListWorkstationClustersResponse, + Awaitable[workstations.ListWorkstationClustersResponse] + ]]: + raise NotImplementedError() + + @property + def create_workstation_cluster(self) -> Callable[ + [workstations.CreateWorkstationClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_workstation_cluster(self) -> Callable[ + [workstations.UpdateWorkstationClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_workstation_cluster(self) -> Callable[ + [workstations.DeleteWorkstationClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_workstation_config(self) -> Callable[ + [workstations.GetWorkstationConfigRequest], + Union[ + workstations.WorkstationConfig, + Awaitable[workstations.WorkstationConfig] + ]]: + raise NotImplementedError() + + @property + def list_workstation_configs(self) -> Callable[ + [workstations.ListWorkstationConfigsRequest], + Union[ + workstations.ListWorkstationConfigsResponse, + Awaitable[workstations.ListWorkstationConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def list_usable_workstation_configs(self) -> Callable[ + [workstations.ListUsableWorkstationConfigsRequest], + Union[ + workstations.ListUsableWorkstationConfigsResponse, + Awaitable[workstations.ListUsableWorkstationConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def create_workstation_config(self) -> Callable[ + [workstations.CreateWorkstationConfigRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_workstation_config(self) -> Callable[ + [workstations.UpdateWorkstationConfigRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_workstation_config(self) -> Callable[ + [workstations.DeleteWorkstationConfigRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_workstation(self) -> Callable[ + [workstations.GetWorkstationRequest], + Union[ + workstations.Workstation, + Awaitable[workstations.Workstation] + ]]: + raise NotImplementedError() + + @property + def list_workstations(self) -> Callable[ + [workstations.ListWorkstationsRequest], + Union[ + workstations.ListWorkstationsResponse, + Awaitable[workstations.ListWorkstationsResponse] + ]]: + raise NotImplementedError() + + @property + def list_usable_workstations(self) -> Callable[ + [workstations.ListUsableWorkstationsRequest], + Union[ + workstations.ListUsableWorkstationsResponse, + Awaitable[workstations.ListUsableWorkstationsResponse] + ]]: + raise NotImplementedError() + + @property + def create_workstation(self) -> Callable[ + [workstations.CreateWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_workstation(self) -> Callable[ + [workstations.UpdateWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_workstation(self) -> Callable[ + [workstations.DeleteWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def start_workstation(self) -> Callable[ + [workstations.StartWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def stop_workstation(self) -> Callable[ + [workstations.StopWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def generate_access_token(self) -> Callable[ + [workstations.GenerateAccessTokenRequest], + Union[ + workstations.GenerateAccessTokenResponse, + Awaitable[workstations.GenerateAccessTokenResponse] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'WorkstationsTransport', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc.py new file mode 100644 index 000000000000..c35226b36b23 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc.py @@ -0,0 +1,943 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1.types import workstations +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 +from google.longrunning import operations_pb2 # type: ignore +from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO + + +class WorkstationsGrpcTransport(WorkstationsTransport): + """gRPC backend transport for Workstations. + + Service for interacting with Cloud Workstations. + + 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 = 'workstations.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 = 'workstations.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_workstation_cluster(self) -> Callable[ + [workstations.GetWorkstationClusterRequest], + workstations.WorkstationCluster]: + r"""Return a callable for the get workstation cluster method over gRPC. + + Returns the requested workstation cluster. + + Returns: + Callable[[~.GetWorkstationClusterRequest], + ~.WorkstationCluster]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: + self._stubs['get_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/GetWorkstationCluster', + request_serializer=workstations.GetWorkstationClusterRequest.serialize, + response_deserializer=workstations.WorkstationCluster.deserialize, + ) + return self._stubs['get_workstation_cluster'] + + @property + def list_workstation_clusters(self) -> Callable[ + [workstations.ListWorkstationClustersRequest], + workstations.ListWorkstationClustersResponse]: + r"""Return a callable for the list workstation clusters method over gRPC. + + Returns all workstation clusters in the specified + location. + + Returns: + Callable[[~.ListWorkstationClustersRequest], + ~.ListWorkstationClustersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_clusters' not in self._stubs: + self._stubs['list_workstation_clusters'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListWorkstationClusters', + request_serializer=workstations.ListWorkstationClustersRequest.serialize, + response_deserializer=workstations.ListWorkstationClustersResponse.deserialize, + ) + return self._stubs['list_workstation_clusters'] + + @property + def create_workstation_cluster(self) -> Callable[ + [workstations.CreateWorkstationClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the create workstation cluster method over gRPC. + + Creates a new workstation cluster. + + Returns: + Callable[[~.CreateWorkstationClusterRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: + self._stubs['create_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/CreateWorkstationCluster', + request_serializer=workstations.CreateWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation_cluster'] + + @property + def update_workstation_cluster(self) -> Callable[ + [workstations.UpdateWorkstationClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the update workstation cluster method over gRPC. + + Updates an existing workstation cluster. + + Returns: + Callable[[~.UpdateWorkstationClusterRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: + self._stubs['update_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/UpdateWorkstationCluster', + request_serializer=workstations.UpdateWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation_cluster'] + + @property + def delete_workstation_cluster(self) -> Callable[ + [workstations.DeleteWorkstationClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete workstation cluster method over gRPC. + + Deletes the specified workstation cluster. + + Returns: + Callable[[~.DeleteWorkstationClusterRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: + self._stubs['delete_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/DeleteWorkstationCluster', + request_serializer=workstations.DeleteWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation_cluster'] + + @property + def get_workstation_config(self) -> Callable[ + [workstations.GetWorkstationConfigRequest], + workstations.WorkstationConfig]: + r"""Return a callable for the get workstation config method over gRPC. + + Returns the requested workstation configuration. + + Returns: + Callable[[~.GetWorkstationConfigRequest], + ~.WorkstationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: + self._stubs['get_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/GetWorkstationConfig', + request_serializer=workstations.GetWorkstationConfigRequest.serialize, + response_deserializer=workstations.WorkstationConfig.deserialize, + ) + return self._stubs['get_workstation_config'] + + @property + def list_workstation_configs(self) -> Callable[ + [workstations.ListWorkstationConfigsRequest], + workstations.ListWorkstationConfigsResponse]: + r"""Return a callable for the list workstation configs method over gRPC. + + Returns all workstation configurations in the + specified cluster. + + Returns: + Callable[[~.ListWorkstationConfigsRequest], + ~.ListWorkstationConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_configs' not in self._stubs: + self._stubs['list_workstation_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListWorkstationConfigs', + request_serializer=workstations.ListWorkstationConfigsRequest.serialize, + response_deserializer=workstations.ListWorkstationConfigsResponse.deserialize, + ) + return self._stubs['list_workstation_configs'] + + @property + def list_usable_workstation_configs(self) -> Callable[ + [workstations.ListUsableWorkstationConfigsRequest], + workstations.ListUsableWorkstationConfigsResponse]: + r"""Return a callable for the list usable workstation + configs method over gRPC. + + Returns all workstation configurations in the + specified cluster on which the caller has the + "workstations.workstation.create" permission. + + Returns: + Callable[[~.ListUsableWorkstationConfigsRequest], + ~.ListUsableWorkstationConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_usable_workstation_configs' not in self._stubs: + self._stubs['list_usable_workstation_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListUsableWorkstationConfigs', + request_serializer=workstations.ListUsableWorkstationConfigsRequest.serialize, + response_deserializer=workstations.ListUsableWorkstationConfigsResponse.deserialize, + ) + return self._stubs['list_usable_workstation_configs'] + + @property + def create_workstation_config(self) -> Callable[ + [workstations.CreateWorkstationConfigRequest], + operations_pb2.Operation]: + r"""Return a callable for the create workstation config method over gRPC. + + Creates a new workstation configuration. + + Returns: + Callable[[~.CreateWorkstationConfigRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: + self._stubs['create_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/CreateWorkstationConfig', + request_serializer=workstations.CreateWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation_config'] + + @property + def update_workstation_config(self) -> Callable[ + [workstations.UpdateWorkstationConfigRequest], + operations_pb2.Operation]: + r"""Return a callable for the update workstation config method over gRPC. + + Updates an existing workstation configuration. + + Returns: + Callable[[~.UpdateWorkstationConfigRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: + self._stubs['update_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/UpdateWorkstationConfig', + request_serializer=workstations.UpdateWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation_config'] + + @property + def delete_workstation_config(self) -> Callable[ + [workstations.DeleteWorkstationConfigRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete workstation config method over gRPC. + + Deletes the specified workstation configuration. + + Returns: + Callable[[~.DeleteWorkstationConfigRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: + self._stubs['delete_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/DeleteWorkstationConfig', + request_serializer=workstations.DeleteWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation_config'] + + @property + def get_workstation(self) -> Callable[ + [workstations.GetWorkstationRequest], + workstations.Workstation]: + r"""Return a callable for the get workstation method over gRPC. + + Returns the requested workstation. + + Returns: + Callable[[~.GetWorkstationRequest], + ~.Workstation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation' not in self._stubs: + self._stubs['get_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/GetWorkstation', + request_serializer=workstations.GetWorkstationRequest.serialize, + response_deserializer=workstations.Workstation.deserialize, + ) + return self._stubs['get_workstation'] + + @property + def list_workstations(self) -> Callable[ + [workstations.ListWorkstationsRequest], + workstations.ListWorkstationsResponse]: + r"""Return a callable for the list workstations method over gRPC. + + Returns all Workstations using the specified + workstation configuration. + + Returns: + Callable[[~.ListWorkstationsRequest], + ~.ListWorkstationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstations' not in self._stubs: + self._stubs['list_workstations'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListWorkstations', + request_serializer=workstations.ListWorkstationsRequest.serialize, + response_deserializer=workstations.ListWorkstationsResponse.deserialize, + ) + return self._stubs['list_workstations'] + + @property + def list_usable_workstations(self) -> Callable[ + [workstations.ListUsableWorkstationsRequest], + workstations.ListUsableWorkstationsResponse]: + r"""Return a callable for the list usable workstations method over gRPC. + + Returns all workstations using the specified + workstation configuration on which the caller has the + "workstations.workstations.use" permission. + + Returns: + Callable[[~.ListUsableWorkstationsRequest], + ~.ListUsableWorkstationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_usable_workstations' not in self._stubs: + self._stubs['list_usable_workstations'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListUsableWorkstations', + request_serializer=workstations.ListUsableWorkstationsRequest.serialize, + response_deserializer=workstations.ListUsableWorkstationsResponse.deserialize, + ) + return self._stubs['list_usable_workstations'] + + @property + def create_workstation(self) -> Callable[ + [workstations.CreateWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the create workstation method over gRPC. + + Creates a new workstation. + + Returns: + Callable[[~.CreateWorkstationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation' not in self._stubs: + self._stubs['create_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/CreateWorkstation', + request_serializer=workstations.CreateWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation'] + + @property + def update_workstation(self) -> Callable[ + [workstations.UpdateWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the update workstation method over gRPC. + + Updates an existing workstation. + + Returns: + Callable[[~.UpdateWorkstationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation' not in self._stubs: + self._stubs['update_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/UpdateWorkstation', + request_serializer=workstations.UpdateWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation'] + + @property + def delete_workstation(self) -> Callable[ + [workstations.DeleteWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete workstation method over gRPC. + + Deletes the specified workstation. + + Returns: + Callable[[~.DeleteWorkstationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation' not in self._stubs: + self._stubs['delete_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/DeleteWorkstation', + request_serializer=workstations.DeleteWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation'] + + @property + def start_workstation(self) -> Callable[ + [workstations.StartWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the start workstation method over gRPC. + + Starts running a workstation so that users can + connect to it. + + Returns: + Callable[[~.StartWorkstationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_workstation' not in self._stubs: + self._stubs['start_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/StartWorkstation', + request_serializer=workstations.StartWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['start_workstation'] + + @property + def stop_workstation(self) -> Callable[ + [workstations.StopWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the stop workstation method over gRPC. + + Stops running a workstation, reducing costs. + + Returns: + Callable[[~.StopWorkstationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_workstation' not in self._stubs: + self._stubs['stop_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/StopWorkstation', + request_serializer=workstations.StopWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['stop_workstation'] + + @property + def generate_access_token(self) -> Callable[ + [workstations.GenerateAccessTokenRequest], + workstations.GenerateAccessTokenResponse]: + r"""Return a callable for the generate access token method over gRPC. + + Returns a short-lived credential that can be used to + send authenticated and authorized traffic to a + workstation. + + Returns: + Callable[[~.GenerateAccessTokenRequest], + ~.GenerateAccessTokenResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_access_token' not in self._stubs: + self._stubs['generate_access_token'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/GenerateAccessToken', + request_serializer=workstations.GenerateAccessTokenRequest.serialize, + response_deserializer=workstations.GenerateAccessTokenResponse.deserialize, + ) + return self._stubs['generate_access_token'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'WorkstationsGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc_asyncio.py new file mode 100644 index 000000000000..ee4f5cfb2018 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc_asyncio.py @@ -0,0 +1,942 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1.types import workstations +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 +from google.longrunning import operations_pb2 # type: ignore +from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO +from .grpc import WorkstationsGrpcTransport + + +class WorkstationsGrpcAsyncIOTransport(WorkstationsTransport): + """gRPC AsyncIO backend transport for Workstations. + + Service for interacting with Cloud Workstations. + + 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 = 'workstations.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 = 'workstations.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_workstation_cluster(self) -> Callable[ + [workstations.GetWorkstationClusterRequest], + Awaitable[workstations.WorkstationCluster]]: + r"""Return a callable for the get workstation cluster method over gRPC. + + Returns the requested workstation cluster. + + Returns: + Callable[[~.GetWorkstationClusterRequest], + Awaitable[~.WorkstationCluster]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: + self._stubs['get_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/GetWorkstationCluster', + request_serializer=workstations.GetWorkstationClusterRequest.serialize, + response_deserializer=workstations.WorkstationCluster.deserialize, + ) + return self._stubs['get_workstation_cluster'] + + @property + def list_workstation_clusters(self) -> Callable[ + [workstations.ListWorkstationClustersRequest], + Awaitable[workstations.ListWorkstationClustersResponse]]: + r"""Return a callable for the list workstation clusters method over gRPC. + + Returns all workstation clusters in the specified + location. + + Returns: + Callable[[~.ListWorkstationClustersRequest], + Awaitable[~.ListWorkstationClustersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_clusters' not in self._stubs: + self._stubs['list_workstation_clusters'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListWorkstationClusters', + request_serializer=workstations.ListWorkstationClustersRequest.serialize, + response_deserializer=workstations.ListWorkstationClustersResponse.deserialize, + ) + return self._stubs['list_workstation_clusters'] + + @property + def create_workstation_cluster(self) -> Callable[ + [workstations.CreateWorkstationClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create workstation cluster method over gRPC. + + Creates a new workstation cluster. + + Returns: + Callable[[~.CreateWorkstationClusterRequest], + 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_workstation_cluster' not in self._stubs: + self._stubs['create_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/CreateWorkstationCluster', + request_serializer=workstations.CreateWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation_cluster'] + + @property + def update_workstation_cluster(self) -> Callable[ + [workstations.UpdateWorkstationClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update workstation cluster method over gRPC. + + Updates an existing workstation cluster. + + Returns: + Callable[[~.UpdateWorkstationClusterRequest], + 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_workstation_cluster' not in self._stubs: + self._stubs['update_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/UpdateWorkstationCluster', + request_serializer=workstations.UpdateWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation_cluster'] + + @property + def delete_workstation_cluster(self) -> Callable[ + [workstations.DeleteWorkstationClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete workstation cluster method over gRPC. + + Deletes the specified workstation cluster. + + Returns: + Callable[[~.DeleteWorkstationClusterRequest], + 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_workstation_cluster' not in self._stubs: + self._stubs['delete_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/DeleteWorkstationCluster', + request_serializer=workstations.DeleteWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation_cluster'] + + @property + def get_workstation_config(self) -> Callable[ + [workstations.GetWorkstationConfigRequest], + Awaitable[workstations.WorkstationConfig]]: + r"""Return a callable for the get workstation config method over gRPC. + + Returns the requested workstation configuration. + + Returns: + Callable[[~.GetWorkstationConfigRequest], + Awaitable[~.WorkstationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: + self._stubs['get_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/GetWorkstationConfig', + request_serializer=workstations.GetWorkstationConfigRequest.serialize, + response_deserializer=workstations.WorkstationConfig.deserialize, + ) + return self._stubs['get_workstation_config'] + + @property + def list_workstation_configs(self) -> Callable[ + [workstations.ListWorkstationConfigsRequest], + Awaitable[workstations.ListWorkstationConfigsResponse]]: + r"""Return a callable for the list workstation configs method over gRPC. + + Returns all workstation configurations in the + specified cluster. + + Returns: + Callable[[~.ListWorkstationConfigsRequest], + Awaitable[~.ListWorkstationConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_configs' not in self._stubs: + self._stubs['list_workstation_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListWorkstationConfigs', + request_serializer=workstations.ListWorkstationConfigsRequest.serialize, + response_deserializer=workstations.ListWorkstationConfigsResponse.deserialize, + ) + return self._stubs['list_workstation_configs'] + + @property + def list_usable_workstation_configs(self) -> Callable[ + [workstations.ListUsableWorkstationConfigsRequest], + Awaitable[workstations.ListUsableWorkstationConfigsResponse]]: + r"""Return a callable for the list usable workstation + configs method over gRPC. + + Returns all workstation configurations in the + specified cluster on which the caller has the + "workstations.workstation.create" permission. + + Returns: + Callable[[~.ListUsableWorkstationConfigsRequest], + Awaitable[~.ListUsableWorkstationConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_usable_workstation_configs' not in self._stubs: + self._stubs['list_usable_workstation_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListUsableWorkstationConfigs', + request_serializer=workstations.ListUsableWorkstationConfigsRequest.serialize, + response_deserializer=workstations.ListUsableWorkstationConfigsResponse.deserialize, + ) + return self._stubs['list_usable_workstation_configs'] + + @property + def create_workstation_config(self) -> Callable[ + [workstations.CreateWorkstationConfigRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create workstation config method over gRPC. + + Creates a new workstation configuration. + + Returns: + Callable[[~.CreateWorkstationConfigRequest], + 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_workstation_config' not in self._stubs: + self._stubs['create_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/CreateWorkstationConfig', + request_serializer=workstations.CreateWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation_config'] + + @property + def update_workstation_config(self) -> Callable[ + [workstations.UpdateWorkstationConfigRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update workstation config method over gRPC. + + Updates an existing workstation configuration. + + Returns: + Callable[[~.UpdateWorkstationConfigRequest], + 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_workstation_config' not in self._stubs: + self._stubs['update_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/UpdateWorkstationConfig', + request_serializer=workstations.UpdateWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation_config'] + + @property + def delete_workstation_config(self) -> Callable[ + [workstations.DeleteWorkstationConfigRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete workstation config method over gRPC. + + Deletes the specified workstation configuration. + + Returns: + Callable[[~.DeleteWorkstationConfigRequest], + 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_workstation_config' not in self._stubs: + self._stubs['delete_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/DeleteWorkstationConfig', + request_serializer=workstations.DeleteWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation_config'] + + @property + def get_workstation(self) -> Callable[ + [workstations.GetWorkstationRequest], + Awaitable[workstations.Workstation]]: + r"""Return a callable for the get workstation method over gRPC. + + Returns the requested workstation. + + Returns: + Callable[[~.GetWorkstationRequest], + Awaitable[~.Workstation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation' not in self._stubs: + self._stubs['get_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/GetWorkstation', + request_serializer=workstations.GetWorkstationRequest.serialize, + response_deserializer=workstations.Workstation.deserialize, + ) + return self._stubs['get_workstation'] + + @property + def list_workstations(self) -> Callable[ + [workstations.ListWorkstationsRequest], + Awaitable[workstations.ListWorkstationsResponse]]: + r"""Return a callable for the list workstations method over gRPC. + + Returns all Workstations using the specified + workstation configuration. + + Returns: + Callable[[~.ListWorkstationsRequest], + Awaitable[~.ListWorkstationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstations' not in self._stubs: + self._stubs['list_workstations'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListWorkstations', + request_serializer=workstations.ListWorkstationsRequest.serialize, + response_deserializer=workstations.ListWorkstationsResponse.deserialize, + ) + return self._stubs['list_workstations'] + + @property + def list_usable_workstations(self) -> Callable[ + [workstations.ListUsableWorkstationsRequest], + Awaitable[workstations.ListUsableWorkstationsResponse]]: + r"""Return a callable for the list usable workstations method over gRPC. + + Returns all workstations using the specified + workstation configuration on which the caller has the + "workstations.workstations.use" permission. + + Returns: + Callable[[~.ListUsableWorkstationsRequest], + Awaitable[~.ListUsableWorkstationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_usable_workstations' not in self._stubs: + self._stubs['list_usable_workstations'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/ListUsableWorkstations', + request_serializer=workstations.ListUsableWorkstationsRequest.serialize, + response_deserializer=workstations.ListUsableWorkstationsResponse.deserialize, + ) + return self._stubs['list_usable_workstations'] + + @property + def create_workstation(self) -> Callable[ + [workstations.CreateWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create workstation method over gRPC. + + Creates a new workstation. + + Returns: + Callable[[~.CreateWorkstationRequest], + 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_workstation' not in self._stubs: + self._stubs['create_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/CreateWorkstation', + request_serializer=workstations.CreateWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation'] + + @property + def update_workstation(self) -> Callable[ + [workstations.UpdateWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update workstation method over gRPC. + + Updates an existing workstation. + + Returns: + Callable[[~.UpdateWorkstationRequest], + 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_workstation' not in self._stubs: + self._stubs['update_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/UpdateWorkstation', + request_serializer=workstations.UpdateWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation'] + + @property + def delete_workstation(self) -> Callable[ + [workstations.DeleteWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete workstation method over gRPC. + + Deletes the specified workstation. + + Returns: + Callable[[~.DeleteWorkstationRequest], + 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_workstation' not in self._stubs: + self._stubs['delete_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/DeleteWorkstation', + request_serializer=workstations.DeleteWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation'] + + @property + def start_workstation(self) -> Callable[ + [workstations.StartWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the start workstation method over gRPC. + + Starts running a workstation so that users can + connect to it. + + Returns: + Callable[[~.StartWorkstationRequest], + 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 'start_workstation' not in self._stubs: + self._stubs['start_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/StartWorkstation', + request_serializer=workstations.StartWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['start_workstation'] + + @property + def stop_workstation(self) -> Callable[ + [workstations.StopWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the stop workstation method over gRPC. + + Stops running a workstation, reducing costs. + + Returns: + Callable[[~.StopWorkstationRequest], + 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 'stop_workstation' not in self._stubs: + self._stubs['stop_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/StopWorkstation', + request_serializer=workstations.StopWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['stop_workstation'] + + @property + def generate_access_token(self) -> Callable[ + [workstations.GenerateAccessTokenRequest], + Awaitable[workstations.GenerateAccessTokenResponse]]: + r"""Return a callable for the generate access token method over gRPC. + + Returns a short-lived credential that can be used to + send authenticated and authorized traffic to a + workstation. + + Returns: + Callable[[~.GenerateAccessTokenRequest], + Awaitable[~.GenerateAccessTokenResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_access_token' not in self._stubs: + self._stubs['generate_access_token'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1.Workstations/GenerateAccessToken', + request_serializer=workstations.GenerateAccessTokenRequest.serialize, + response_deserializer=workstations.GenerateAccessTokenResponse.deserialize, + ) + return self._stubs['generate_access_token'] + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'WorkstationsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest.py new file mode 100644 index 000000000000..71d5eb89f24b --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest.py @@ -0,0 +1,3177 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.workstations_v1.types import workstations +from google.longrunning import operations_pb2 # type: ignore + +from .base import WorkstationsTransport, 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 WorkstationsRestInterceptor: + """Interceptor for Workstations. + + 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 WorkstationsRestTransport. + + .. code-block:: python + class MyCustomWorkstationsInterceptor(WorkstationsRestInterceptor): + def pre_create_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_workstation_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_workstation_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_workstation_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_workstation_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_workstation_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_workstation_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_workstation_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_workstation_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_access_token(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_access_token(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_workstation_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_workstation_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_workstation_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_workstation_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_usable_workstation_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_usable_workstation_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_usable_workstations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_usable_workstations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_workstation_clusters(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_workstation_clusters(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_workstation_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_workstation_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_workstations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_workstations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_start_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_start_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_stop_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_stop_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_workstation_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_workstation_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_workstation_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_workstation_config(self, response): + logging.log(f"Received response: {response}") + return response + + transport = WorkstationsRestTransport(interceptor=MyCustomWorkstationsInterceptor()) + client = WorkstationsClient(transport=transport) + + + """ + def pre_create_workstation(self, request: workstations.CreateWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_create_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_create_workstation_cluster(self, request: workstations.CreateWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_workstation_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_create_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_workstation_cluster + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_create_workstation_config(self, request: workstations.CreateWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_workstation_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_create_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_workstation_config + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_delete_workstation(self, request: workstations.DeleteWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_delete_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_delete_workstation_cluster(self, request: workstations.DeleteWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_workstation_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_delete_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_workstation_cluster + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_delete_workstation_config(self, request: workstations.DeleteWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_workstation_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_delete_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_workstation_config + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_generate_access_token(self, request: workstations.GenerateAccessTokenRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GenerateAccessTokenRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_access_token + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_generate_access_token(self, response: workstations.GenerateAccessTokenResponse) -> workstations.GenerateAccessTokenResponse: + """Post-rpc interceptor for generate_access_token + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_get_workstation(self, request: workstations.GetWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_get_workstation(self, response: workstations.Workstation) -> workstations.Workstation: + """Post-rpc interceptor for get_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_get_workstation_cluster(self, request: workstations.GetWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_workstation_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_get_workstation_cluster(self, response: workstations.WorkstationCluster) -> workstations.WorkstationCluster: + """Post-rpc interceptor for get_workstation_cluster + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_get_workstation_config(self, request: workstations.GetWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_workstation_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_get_workstation_config(self, response: workstations.WorkstationConfig) -> workstations.WorkstationConfig: + """Post-rpc interceptor for get_workstation_config + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_list_usable_workstation_configs(self, request: workstations.ListUsableWorkstationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListUsableWorkstationConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_usable_workstation_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_usable_workstation_configs(self, response: workstations.ListUsableWorkstationConfigsResponse) -> workstations.ListUsableWorkstationConfigsResponse: + """Post-rpc interceptor for list_usable_workstation_configs + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_list_usable_workstations(self, request: workstations.ListUsableWorkstationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListUsableWorkstationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_usable_workstations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_usable_workstations(self, response: workstations.ListUsableWorkstationsResponse) -> workstations.ListUsableWorkstationsResponse: + """Post-rpc interceptor for list_usable_workstations + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_list_workstation_clusters(self, request: workstations.ListWorkstationClustersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationClustersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_workstation_clusters + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_workstation_clusters(self, response: workstations.ListWorkstationClustersResponse) -> workstations.ListWorkstationClustersResponse: + """Post-rpc interceptor for list_workstation_clusters + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_list_workstation_configs(self, request: workstations.ListWorkstationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_workstation_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_workstation_configs(self, response: workstations.ListWorkstationConfigsResponse) -> workstations.ListWorkstationConfigsResponse: + """Post-rpc interceptor for list_workstation_configs + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_list_workstations(self, request: workstations.ListWorkstationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_workstations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_workstations(self, response: workstations.ListWorkstationsResponse) -> workstations.ListWorkstationsResponse: + """Post-rpc interceptor for list_workstations + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_start_workstation(self, request: workstations.StartWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.StartWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for start_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_start_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for start_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_stop_workstation(self, request: workstations.StopWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.StopWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for stop_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_stop_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for stop_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_update_workstation(self, request: workstations.UpdateWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_update_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_update_workstation_cluster(self, request: workstations.UpdateWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_workstation_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_update_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_workstation_cluster + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_update_workstation_config(self, request: workstations.UpdateWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_workstation_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_update_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_workstation_config + + Override in a subclass to manipulate the response + after it is returned by the Workstations 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 Workstations 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 Workstations 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 Workstations 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 Workstations 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 Workstations 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 Workstations server but before + it is returned to user code. + """ + return response + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class WorkstationsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: WorkstationsRestInterceptor + + +class WorkstationsRestTransport(WorkstationsTransport): + """REST backend transport for Workstations. + + Service for interacting with Cloud Workstations. + + 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 = 'workstations.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[WorkstationsRestInterceptor] = 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 WorkstationsRestInterceptor() + 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.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateWorkstation(WorkstationsRestStub): + def __hash__(self): + return hash("CreateWorkstation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "workstationId" : "", } + + @classmethod + def _get_unset_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: workstations.CreateWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create workstation method over HTTP. + + Args: + request (~.workstations.CreateWorkstationRequest): + The request object. Message for creating a + CreateWorkstation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations', + 'body': 'workstation', + }, + ] + request, metadata = self._interceptor.pre_create_workstation(request, metadata) + pb_request = workstations.CreateWorkstationRequest.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_workstation(resp) + return resp + + class _CreateWorkstationCluster(WorkstationsRestStub): + def __hash__(self): + return hash("CreateWorkstationCluster") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "workstationClusterId" : "", } + + @classmethod + def _get_unset_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: workstations.CreateWorkstationClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create workstation + cluster method over HTTP. + + Args: + request (~.workstations.CreateWorkstationClusterRequest): + The request object. Message for creating a + CreateWorkstationCluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/workstationClusters', + 'body': 'workstation_cluster', + }, + ] + request, metadata = self._interceptor.pre_create_workstation_cluster(request, metadata) + pb_request = workstations.CreateWorkstationClusterRequest.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_workstation_cluster(resp) + return resp + + class _CreateWorkstationConfig(WorkstationsRestStub): + def __hash__(self): + return hash("CreateWorkstationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "workstationConfigId" : "", } + + @classmethod + def _get_unset_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: workstations.CreateWorkstationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create workstation config method over HTTP. + + Args: + request (~.workstations.CreateWorkstationConfigRequest): + The request object. Message for creating a + CreateWorkstationConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs', + 'body': 'workstation_config', + }, + ] + request, metadata = self._interceptor.pre_create_workstation_config(request, metadata) + pb_request = workstations.CreateWorkstationConfigRequest.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_workstation_config(resp) + return resp + + class _DeleteWorkstation(WorkstationsRestStub): + def __hash__(self): + return hash("DeleteWorkstation") + + __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: workstations.DeleteWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete workstation method over HTTP. + + Args: + request (~.workstations.DeleteWorkstationRequest): + The request object. Request message for + DeleteWorkstation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_workstation(request, metadata) + pb_request = workstations.DeleteWorkstationRequest.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_workstation(resp) + return resp + + class _DeleteWorkstationCluster(WorkstationsRestStub): + def __hash__(self): + return hash("DeleteWorkstationCluster") + + __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: workstations.DeleteWorkstationClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete workstation + cluster method over HTTP. + + Args: + request (~.workstations.DeleteWorkstationClusterRequest): + The request object. Message for deleting a workstation + cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_workstation_cluster(request, metadata) + pb_request = workstations.DeleteWorkstationClusterRequest.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_workstation_cluster(resp) + return resp + + class _DeleteWorkstationConfig(WorkstationsRestStub): + def __hash__(self): + return hash("DeleteWorkstationConfig") + + __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: workstations.DeleteWorkstationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete workstation config method over HTTP. + + Args: + request (~.workstations.DeleteWorkstationConfigRequest): + The request object. Message for deleting a workstation + configuration. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_workstation_config(request, metadata) + pb_request = workstations.DeleteWorkstationConfigRequest.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_workstation_config(resp) + return resp + + class _GenerateAccessToken(WorkstationsRestStub): + def __hash__(self): + return hash("GenerateAccessToken") + + __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: workstations.GenerateAccessTokenRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.GenerateAccessTokenResponse: + r"""Call the generate access token method over HTTP. + + Args: + request (~.workstations.GenerateAccessTokenRequest): + The request object. Request message for + GenerateAccessToken. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.workstations.GenerateAccessTokenResponse: + Response message for + GenerateAccessToken. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{workstation=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:generateAccessToken', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_generate_access_token(request, metadata) + pb_request = workstations.GenerateAccessTokenRequest.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 = workstations.GenerateAccessTokenResponse() + pb_resp = workstations.GenerateAccessTokenResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_access_token(resp) + return resp + + class _GetWorkstation(WorkstationsRestStub): + def __hash__(self): + return hash("GetWorkstation") + + __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: workstations.GetWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.Workstation: + r"""Call the get workstation method over HTTP. + + Args: + request (~.workstations.GetWorkstationRequest): + The request object. Request message for GetWorkstation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.workstations.Workstation: + A single instance of a developer + workstation with its own persistent + storage. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', + }, + ] + request, metadata = self._interceptor.pre_get_workstation(request, metadata) + pb_request = workstations.GetWorkstationRequest.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 = workstations.Workstation() + pb_resp = workstations.Workstation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_workstation(resp) + return resp + + class _GetWorkstationCluster(WorkstationsRestStub): + def __hash__(self): + return hash("GetWorkstationCluster") + + __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: workstations.GetWorkstationClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.WorkstationCluster: + r"""Call the get workstation cluster method over HTTP. + + Args: + request (~.workstations.GetWorkstationClusterRequest): + The request object. Request message for + GetWorkstationCluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.workstations.WorkstationCluster: + A grouping of workstation + configurations and the associated + workstations in that region. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*}', + }, + ] + request, metadata = self._interceptor.pre_get_workstation_cluster(request, metadata) + pb_request = workstations.GetWorkstationClusterRequest.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 = workstations.WorkstationCluster() + pb_resp = workstations.WorkstationCluster.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_workstation_cluster(resp) + return resp + + class _GetWorkstationConfig(WorkstationsRestStub): + def __hash__(self): + return hash("GetWorkstationConfig") + + __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: workstations.GetWorkstationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.WorkstationConfig: + r"""Call the get workstation config method over HTTP. + + Args: + request (~.workstations.GetWorkstationConfigRequest): + The request object. Request message for + GetWorkstationConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.workstations.WorkstationConfig: + A set of configuration options + describing how a workstation will be + run. Workstation configurations are + intended to be shared across multiple + workstations. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_workstation_config(request, metadata) + pb_request = workstations.GetWorkstationConfigRequest.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 = workstations.WorkstationConfig() + pb_resp = workstations.WorkstationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_workstation_config(resp) + return resp + + class _ListUsableWorkstationConfigs(WorkstationsRestStub): + def __hash__(self): + return hash("ListUsableWorkstationConfigs") + + __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: workstations.ListUsableWorkstationConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListUsableWorkstationConfigsResponse: + r"""Call the list usable workstation + configs method over HTTP. + + Args: + request (~.workstations.ListUsableWorkstationConfigsRequest): + The request object. Request message for + ListUsableWorkstationConfigs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.workstations.ListUsableWorkstationConfigsResponse: + Response message for + ListUsableWorkstationConfigs. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs:listUsable', + }, + ] + request, metadata = self._interceptor.pre_list_usable_workstation_configs(request, metadata) + pb_request = workstations.ListUsableWorkstationConfigsRequest.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 = workstations.ListUsableWorkstationConfigsResponse() + pb_resp = workstations.ListUsableWorkstationConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_usable_workstation_configs(resp) + return resp + + class _ListUsableWorkstations(WorkstationsRestStub): + def __hash__(self): + return hash("ListUsableWorkstations") + + __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: workstations.ListUsableWorkstationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListUsableWorkstationsResponse: + r"""Call the list usable workstations method over HTTP. + + Args: + request (~.workstations.ListUsableWorkstationsRequest): + The request object. Request message for + ListUsableWorkstations. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.workstations.ListUsableWorkstationsResponse: + Response message for + ListUsableWorkstations. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations:listUsable', + }, + ] + request, metadata = self._interceptor.pre_list_usable_workstations(request, metadata) + pb_request = workstations.ListUsableWorkstationsRequest.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 = workstations.ListUsableWorkstationsResponse() + pb_resp = workstations.ListUsableWorkstationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_usable_workstations(resp) + return resp + + class _ListWorkstationClusters(WorkstationsRestStub): + def __hash__(self): + return hash("ListWorkstationClusters") + + __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: workstations.ListWorkstationClustersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListWorkstationClustersResponse: + r"""Call the list workstation clusters method over HTTP. + + Args: + request (~.workstations.ListWorkstationClustersRequest): + The request object. Request message for + ListWorkstationClusters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.workstations.ListWorkstationClustersResponse: + Response message for + ListWorkstationClusters. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/workstationClusters', + }, + ] + request, metadata = self._interceptor.pre_list_workstation_clusters(request, metadata) + pb_request = workstations.ListWorkstationClustersRequest.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 = workstations.ListWorkstationClustersResponse() + pb_resp = workstations.ListWorkstationClustersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_workstation_clusters(resp) + return resp + + class _ListWorkstationConfigs(WorkstationsRestStub): + def __hash__(self): + return hash("ListWorkstationConfigs") + + __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: workstations.ListWorkstationConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListWorkstationConfigsResponse: + r"""Call the list workstation configs method over HTTP. + + Args: + request (~.workstations.ListWorkstationConfigsRequest): + The request object. Request message for + ListWorkstationConfigs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.workstations.ListWorkstationConfigsResponse: + Response message for + ListWorkstationConfigs. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs', + }, + ] + request, metadata = self._interceptor.pre_list_workstation_configs(request, metadata) + pb_request = workstations.ListWorkstationConfigsRequest.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 = workstations.ListWorkstationConfigsResponse() + pb_resp = workstations.ListWorkstationConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_workstation_configs(resp) + return resp + + class _ListWorkstations(WorkstationsRestStub): + def __hash__(self): + return hash("ListWorkstations") + + __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: workstations.ListWorkstationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListWorkstationsResponse: + r"""Call the list workstations method over HTTP. + + Args: + request (~.workstations.ListWorkstationsRequest): + The request object. Request message for ListWorkstations. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.workstations.ListWorkstationsResponse: + Response message for + ListWorkstations. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations', + }, + ] + request, metadata = self._interceptor.pre_list_workstations(request, metadata) + pb_request = workstations.ListWorkstationsRequest.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 = workstations.ListWorkstationsResponse() + pb_resp = workstations.ListWorkstationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_workstations(resp) + return resp + + class _StartWorkstation(WorkstationsRestStub): + def __hash__(self): + return hash("StartWorkstation") + + __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: workstations.StartWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the start workstation method over HTTP. + + Args: + request (~.workstations.StartWorkstationRequest): + The request object. Request message for StartWorkstation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:start', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_start_workstation(request, metadata) + pb_request = workstations.StartWorkstationRequest.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_start_workstation(resp) + return resp + + class _StopWorkstation(WorkstationsRestStub): + def __hash__(self): + return hash("StopWorkstation") + + __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: workstations.StopWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the stop workstation method over HTTP. + + Args: + request (~.workstations.StopWorkstationRequest): + The request object. Request message for StopWorkstation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:stop', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_stop_workstation(request, metadata) + pb_request = workstations.StopWorkstationRequest.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_stop_workstation(resp) + return resp + + class _UpdateWorkstation(WorkstationsRestStub): + def __hash__(self): + return hash("UpdateWorkstation") + + __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: workstations.UpdateWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update workstation method over HTTP. + + Args: + request (~.workstations.UpdateWorkstationRequest): + The request object. Request message for + UpdateWorkstation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{workstation.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', + 'body': 'workstation', + }, + ] + request, metadata = self._interceptor.pre_update_workstation(request, metadata) + pb_request = workstations.UpdateWorkstationRequest.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_workstation(resp) + return resp + + class _UpdateWorkstationCluster(WorkstationsRestStub): + def __hash__(self): + return hash("UpdateWorkstationCluster") + + __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: workstations.UpdateWorkstationClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update workstation + cluster method over HTTP. + + Args: + request (~.workstations.UpdateWorkstationClusterRequest): + The request object. Request message for + UpdateWorkstationCluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{workstation_cluster.name=projects/*/locations/*/workstationClusters/*}', + 'body': 'workstation_cluster', + }, + ] + request, metadata = self._interceptor.pre_update_workstation_cluster(request, metadata) + pb_request = workstations.UpdateWorkstationClusterRequest.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_workstation_cluster(resp) + return resp + + class _UpdateWorkstationConfig(WorkstationsRestStub): + def __hash__(self): + return hash("UpdateWorkstationConfig") + + __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: workstations.UpdateWorkstationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update workstation config method over HTTP. + + Args: + request (~.workstations.UpdateWorkstationConfigRequest): + The request object. Request message for + UpdateWorkstationConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{workstation_config.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', + 'body': 'workstation_config', + }, + ] + request, metadata = self._interceptor.pre_update_workstation_config(request, metadata) + pb_request = workstations.UpdateWorkstationConfigRequest.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_workstation_config(resp) + return resp + + @property + def create_workstation(self) -> Callable[ + [workstations.CreateWorkstationRequest], + 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._CreateWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_workstation_cluster(self) -> Callable[ + [workstations.CreateWorkstationClusterRequest], + 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._CreateWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_workstation_config(self) -> Callable[ + [workstations.CreateWorkstationConfigRequest], + 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._CreateWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_workstation(self) -> Callable[ + [workstations.DeleteWorkstationRequest], + 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._DeleteWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_workstation_cluster(self) -> Callable[ + [workstations.DeleteWorkstationClusterRequest], + 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._DeleteWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_workstation_config(self) -> Callable[ + [workstations.DeleteWorkstationConfigRequest], + 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._DeleteWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_access_token(self) -> Callable[ + [workstations.GenerateAccessTokenRequest], + workstations.GenerateAccessTokenResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateAccessToken(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_workstation(self) -> Callable[ + [workstations.GetWorkstationRequest], + workstations.Workstation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_workstation_cluster(self) -> Callable[ + [workstations.GetWorkstationClusterRequest], + workstations.WorkstationCluster]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_workstation_config(self) -> Callable[ + [workstations.GetWorkstationConfigRequest], + workstations.WorkstationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_usable_workstation_configs(self) -> Callable[ + [workstations.ListUsableWorkstationConfigsRequest], + workstations.ListUsableWorkstationConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListUsableWorkstationConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_usable_workstations(self) -> Callable[ + [workstations.ListUsableWorkstationsRequest], + workstations.ListUsableWorkstationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListUsableWorkstations(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_workstation_clusters(self) -> Callable[ + [workstations.ListWorkstationClustersRequest], + workstations.ListWorkstationClustersResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListWorkstationClusters(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_workstation_configs(self) -> Callable[ + [workstations.ListWorkstationConfigsRequest], + workstations.ListWorkstationConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListWorkstationConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_workstations(self) -> Callable[ + [workstations.ListWorkstationsRequest], + workstations.ListWorkstationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListWorkstations(self._session, self._host, self._interceptor) # type: ignore + + @property + def start_workstation(self) -> Callable[ + [workstations.StartWorkstationRequest], + 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._StartWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def stop_workstation(self) -> Callable[ + [workstations.StopWorkstationRequest], + 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._StopWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_workstation(self) -> Callable[ + [workstations.UpdateWorkstationRequest], + 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._UpdateWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_workstation_cluster(self) -> Callable[ + [workstations.UpdateWorkstationClusterRequest], + 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._UpdateWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_workstation_config(self) -> Callable[ + [workstations.UpdateWorkstationConfigRequest], + 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._UpdateWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(WorkstationsRestStub): + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:getIamPolicy', + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(WorkstationsRestStub): + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:setIamPolicy', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + 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) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(WorkstationsRestStub): + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:testIamPermissions', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + 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) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(WorkstationsRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + 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 self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(WorkstationsRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(WorkstationsRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(WorkstationsRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'WorkstationsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/__init__.py new file mode 100644 index 000000000000..78e68e36bfd4 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/__init__.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .workstations import ( + CreateWorkstationClusterRequest, + CreateWorkstationConfigRequest, + CreateWorkstationRequest, + DeleteWorkstationClusterRequest, + DeleteWorkstationConfigRequest, + DeleteWorkstationRequest, + GenerateAccessTokenRequest, + GenerateAccessTokenResponse, + GetWorkstationClusterRequest, + GetWorkstationConfigRequest, + GetWorkstationRequest, + ListUsableWorkstationConfigsRequest, + ListUsableWorkstationConfigsResponse, + ListUsableWorkstationsRequest, + ListUsableWorkstationsResponse, + ListWorkstationClustersRequest, + ListWorkstationClustersResponse, + ListWorkstationConfigsRequest, + ListWorkstationConfigsResponse, + ListWorkstationsRequest, + ListWorkstationsResponse, + OperationMetadata, + StartWorkstationRequest, + StopWorkstationRequest, + UpdateWorkstationClusterRequest, + UpdateWorkstationConfigRequest, + UpdateWorkstationRequest, + Workstation, + WorkstationCluster, + WorkstationConfig, +) + +__all__ = ( + 'CreateWorkstationClusterRequest', + 'CreateWorkstationConfigRequest', + 'CreateWorkstationRequest', + 'DeleteWorkstationClusterRequest', + 'DeleteWorkstationConfigRequest', + 'DeleteWorkstationRequest', + 'GenerateAccessTokenRequest', + 'GenerateAccessTokenResponse', + 'GetWorkstationClusterRequest', + 'GetWorkstationConfigRequest', + 'GetWorkstationRequest', + 'ListUsableWorkstationConfigsRequest', + 'ListUsableWorkstationConfigsResponse', + 'ListUsableWorkstationsRequest', + 'ListUsableWorkstationsResponse', + 'ListWorkstationClustersRequest', + 'ListWorkstationClustersResponse', + 'ListWorkstationConfigsRequest', + 'ListWorkstationConfigsResponse', + 'ListWorkstationsRequest', + 'ListWorkstationsResponse', + 'OperationMetadata', + 'StartWorkstationRequest', + 'StopWorkstationRequest', + 'UpdateWorkstationClusterRequest', + 'UpdateWorkstationConfigRequest', + 'UpdateWorkstationRequest', + 'Workstation', + 'WorkstationCluster', + 'WorkstationConfig', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/workstations.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/workstations.py new file mode 100644 index 000000000000..b82525ca4459 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/workstations.py @@ -0,0 +1,1722 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.workstations.v1', + manifest={ + 'WorkstationCluster', + 'WorkstationConfig', + 'Workstation', + 'GetWorkstationClusterRequest', + 'ListWorkstationClustersRequest', + 'ListWorkstationClustersResponse', + 'CreateWorkstationClusterRequest', + 'UpdateWorkstationClusterRequest', + 'DeleteWorkstationClusterRequest', + 'GetWorkstationConfigRequest', + 'ListWorkstationConfigsRequest', + 'ListWorkstationConfigsResponse', + 'ListUsableWorkstationConfigsRequest', + 'ListUsableWorkstationConfigsResponse', + 'CreateWorkstationConfigRequest', + 'UpdateWorkstationConfigRequest', + 'DeleteWorkstationConfigRequest', + 'GetWorkstationRequest', + 'ListWorkstationsRequest', + 'ListWorkstationsResponse', + 'ListUsableWorkstationsRequest', + 'ListUsableWorkstationsResponse', + 'CreateWorkstationRequest', + 'UpdateWorkstationRequest', + 'DeleteWorkstationRequest', + 'StartWorkstationRequest', + 'StopWorkstationRequest', + 'GenerateAccessTokenRequest', + 'GenerateAccessTokenResponse', + 'OperationMetadata', + }, +) + + +class WorkstationCluster(proto.Message): + r"""A grouping of workstation configurations and the associated + workstations in that region. + + Attributes: + name (str): + Full name of this resource. + display_name (str): + Human-readable name for this resource. + uid (str): + Output only. A system-assigned unique + identified for this resource. + reconciling (bool): + Output only. Indicates whether this resource + is currently being updated to match its intended + state. + annotations (MutableMapping[str, str]): + Client-specified annotations. + labels (MutableMapping[str, str]): + Client-specified labels that are applied to + the resource and that are also propagated to the + underlying Compute Engine resources. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this resource was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this resource was most + recently updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this resource was + soft-deleted. + etag (str): + Checksum computed by the server. May be sent + on update and delete requests to make sure that + the client has an up-to-date value before + proceeding. + network (str): + Immutable. Name of the Compute Engine network + in which instances associated with this cluster + will be created. + subnetwork (str): + Immutable. Name of the Compute Engine + subnetwork in which instances associated with + this cluster will be created. Must be part of + the subnetwork specified for this cluster. + control_plane_ip (str): + Output only. The private IP address of the + control plane for this cluster. Workstation VMs + need access to this IP address to work with the + service, so make sure that your firewall rules + allow egress from the workstation VMs to this + address. + private_cluster_config (google.cloud.workstations_v1.types.WorkstationCluster.PrivateClusterConfig): + Configuration for private cluster. + degraded (bool): + Output only. Whether this resource is in degraded mode, in + which case it may require user action to restore full + functionality. Details can be found in the ``conditions`` + field. + conditions (MutableSequence[google.rpc.status_pb2.Status]): + Output only. Status conditions describing the + current resource state. + """ + + class PrivateClusterConfig(proto.Message): + r"""Configuration options for private clusters. + + Attributes: + enable_private_endpoint (bool): + Immutable. Whether Workstations endpoint is + private. + cluster_hostname (str): + Output only. Hostname for the workstation + cluster. This field will be populated only when + private endpoint is enabled. To access + workstations in the cluster, create a new DNS + zone mapping this domain name to an internal IP + address and a forwarding rule mapping that + address to the service attachment. + service_attachment_uri (str): + Output only. Service attachment URI for the workstation + cluster. The service attachemnt is created when private + endpoint is enabled. To access workstations in the cluster, + configure access to the managed service using `Private + Service + Connect `__. + allowed_projects (MutableSequence[str]): + Additional projects that are allowed to + attach to the workstation cluster's service + attachment. By default, the workstation + cluster's project and the VPC host project (if + different) are allowed. + """ + + enable_private_endpoint: bool = proto.Field( + proto.BOOL, + number=1, + ) + cluster_hostname: str = proto.Field( + proto.STRING, + number=2, + ) + service_attachment_uri: str = proto.Field( + proto.STRING, + number=3, + ) + allowed_projects: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=15, + ) + 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, + ) + network: str = proto.Field( + proto.STRING, + number=10, + ) + subnetwork: str = proto.Field( + proto.STRING, + number=11, + ) + control_plane_ip: str = proto.Field( + proto.STRING, + number=16, + ) + private_cluster_config: PrivateClusterConfig = proto.Field( + proto.MESSAGE, + number=12, + message=PrivateClusterConfig, + ) + degraded: bool = proto.Field( + proto.BOOL, + number=13, + ) + conditions: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=status_pb2.Status, + ) + + +class WorkstationConfig(proto.Message): + r"""A set of configuration options describing how a workstation + will be run. Workstation configurations are intended to be + shared across multiple workstations. + + Attributes: + name (str): + Full name of this resource. + display_name (str): + Human-readable name for this resource. + uid (str): + Output only. A system-assigned unique + identified for this resource. + reconciling (bool): + Output only. Indicates whether this resource + is currently being updated to match its intended + state. + annotations (MutableMapping[str, str]): + Client-specified annotations. + labels (MutableMapping[str, str]): + Client-specified labels that are applied to + the resource and that are also propagated to the + underlying Compute Engine resources. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this resource was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this resource was most + recently updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this resource was + soft-deleted. + etag (str): + Checksum computed by the server. May be sent + on update and delete requests to make sure that + the client has an up-to-date value before + proceeding. + idle_timeout (google.protobuf.duration_pb2.Duration): + How long to wait before automatically + stopping an instance that hasn't received any + user traffic. A value of 0 indicates that this + instance should never time out due to idleness. + Defaults to 20 minutes. + running_timeout (google.protobuf.duration_pb2.Duration): + How long to wait before automatically stopping a workstation + after it started. A value of 0 indicates that workstations + using this configuration should never time out. Must be + greater than 0 and less than 24 hours if encryption_key is + set. Defaults to 12 hours. + host (google.cloud.workstations_v1.types.WorkstationConfig.Host): + Runtime host for the workstation. + persistent_directories (MutableSequence[google.cloud.workstations_v1.types.WorkstationConfig.PersistentDirectory]): + Directories to persist across workstation + sessions. + container (google.cloud.workstations_v1.types.WorkstationConfig.Container): + Container that will be run for each + workstation using this configuration when that + workstation is started. + encryption_key (google.cloud.workstations_v1.types.WorkstationConfig.CustomerEncryptionKey): + Immutable. Encrypts resources of this + workstation configuration using a + customer-managed encryption key. + If specified, the boot disk of the Compute + Engine instance and the persistent disk are + encrypted using this encryption key. If this + field is not set, the disks are encrypted using + a generated key. Customer-managed encryption + keys do not protect disk metadata. + If the customer-managed encryption key is + rotated, when the workstation instance is + stopped, the system attempts to recreate the + persistent disk with the new version of the key. + Be sure to keep older versions of the key until + the persistent disk is recreated. Otherwise, + data on the persistent disk will be lost. + If the encryption key is revoked, the + workstation session will automatically be + stopped within 7 hours. + + Immutable after the workstation configuration is + created. + degraded (bool): + Output only. Whether this resource is degraded, in which + case it may require user action to restore full + functionality. See also the ``conditions`` field. + conditions (MutableSequence[google.rpc.status_pb2.Status]): + Output only. Status conditions describing the + current resource state. + """ + + class Host(proto.Message): + r"""Runtime host for a workstation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gce_instance (google.cloud.workstations_v1.types.WorkstationConfig.Host.GceInstance): + Specifies a Compute Engine instance as the + host. + + This field is a member of `oneof`_ ``config``. + """ + + class GceInstance(proto.Message): + r"""A runtime using a Compute Engine instance. + + Attributes: + machine_type (str): + The name of a Compute Engine machine type. + service_account (str): + Email address of the service account used on + VM instances used to support this configuration. + If not set, VMs run with a Google-managed + service account. This service account must have + permission to pull the specified container + image; otherwise, the image must be publicly + accessible. + tags (MutableSequence[str]): + Network tags to add to the Compute Engine + machines backing the Workstations. + pool_size (int): + Number of instances to pool for faster + workstation startup. + pooled_instances (int): + Output only. Number of instances currently + available in the pool for faster workstation + startup. + disable_public_ip_addresses (bool): + Whether instances have no public IP address. + enable_nested_virtualization (bool): + Whether to enable nested virtualization on + instances. + shielded_instance_config (google.cloud.workstations_v1.types.WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig): + A set of Compute Engine Shielded instance + options. + confidential_instance_config (google.cloud.workstations_v1.types.WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig): + A set of Compute Engine Confidential VM + instance options. + boot_disk_size_gb (int): + Size of the boot disk in GB. Defaults to 50. + """ + + class GceShieldedInstanceConfig(proto.Message): + r"""A set of Compute Engine Shielded instance options. + + Attributes: + enable_secure_boot (bool): + Whether the instance has Secure Boot enabled. + enable_vtpm (bool): + Whether the instance has the vTPM enabled. + enable_integrity_monitoring (bool): + Whether the instance has integrity monitoring + enabled. + """ + + enable_secure_boot: bool = proto.Field( + proto.BOOL, + number=1, + ) + enable_vtpm: bool = proto.Field( + proto.BOOL, + number=2, + ) + enable_integrity_monitoring: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class GceConfidentialInstanceConfig(proto.Message): + r"""A set of Compute Engine Confidential VM instance options. + + Attributes: + enable_confidential_compute (bool): + Whether the instance has confidential compute + enabled. + """ + + enable_confidential_compute: bool = proto.Field( + proto.BOOL, + number=1, + ) + + machine_type: str = proto.Field( + proto.STRING, + number=1, + ) + service_account: str = proto.Field( + proto.STRING, + number=2, + ) + tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + pool_size: int = proto.Field( + proto.INT32, + number=5, + ) + pooled_instances: int = proto.Field( + proto.INT32, + number=12, + ) + disable_public_ip_addresses: bool = proto.Field( + proto.BOOL, + number=6, + ) + enable_nested_virtualization: bool = proto.Field( + proto.BOOL, + number=7, + ) + shielded_instance_config: 'WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig' = proto.Field( + proto.MESSAGE, + number=8, + message='WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig', + ) + confidential_instance_config: 'WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig' = proto.Field( + proto.MESSAGE, + number=10, + message='WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig', + ) + boot_disk_size_gb: int = proto.Field( + proto.INT32, + number=9, + ) + + gce_instance: 'WorkstationConfig.Host.GceInstance' = proto.Field( + proto.MESSAGE, + number=1, + oneof='config', + message='WorkstationConfig.Host.GceInstance', + ) + + class PersistentDirectory(proto.Message): + r"""A directory to persist across workstation sessions. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gce_pd (google.cloud.workstations_v1.types.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk): + A PersistentDirectory backed by a Compute + Engine persistent disk. + + This field is a member of `oneof`_ ``directory_type``. + mount_path (str): + Location of this directory in the running + workstation. + """ + + class GceRegionalPersistentDisk(proto.Message): + r"""A PersistentDirectory backed by a Compute Engine regional + persistent disk. + + Attributes: + size_gb (int): + Size of the disk in GB. Must be empty if source_snapshot is + set. Defaults to 200. + fs_type (str): + Type of file system that the disk should be formatted with. + The workstation image must support this file system type. + Must be empty if source_snapshot is set. Defaults to ext4. + disk_type (str): + Type of the disk to use. Defaults to + pd-standard. + source_snapshot (str): + Name of the snapshot to use as the source for the disk. If + set, size_gb and fs_type must be empty. + reclaim_policy (google.cloud.workstations_v1.types.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy): + What should happen to the disk after the + workstation is deleted. Defaults to DELETE. + """ + class ReclaimPolicy(proto.Enum): + r"""Value representing what should happen to the disk after the + workstation is deleted. + + Values: + RECLAIM_POLICY_UNSPECIFIED (0): + Do not use. + DELETE (1): + The persistent disk will be deleted with the + workstation. + RETAIN (2): + The persistent disk will be remain after the + workstation is deleted, and the administrator + must manually delete the disk. + """ + RECLAIM_POLICY_UNSPECIFIED = 0 + DELETE = 1 + RETAIN = 2 + + size_gb: int = proto.Field( + proto.INT32, + number=1, + ) + fs_type: str = proto.Field( + proto.STRING, + number=2, + ) + disk_type: str = proto.Field( + proto.STRING, + number=3, + ) + source_snapshot: str = proto.Field( + proto.STRING, + number=5, + ) + reclaim_policy: 'WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy' = proto.Field( + proto.ENUM, + number=4, + enum='WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy', + ) + + gce_pd: 'WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk' = proto.Field( + proto.MESSAGE, + number=2, + oneof='directory_type', + message='WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk', + ) + mount_path: str = proto.Field( + proto.STRING, + number=1, + ) + + class Container(proto.Message): + r"""A Docker container. + + Attributes: + image (str): + Docker image defining the container. This + image must be accessible by the service account + specified in the workstation configuration. + command (MutableSequence[str]): + If set, overrides the default ENTRYPOINT + specified by the image. + args (MutableSequence[str]): + Arguments passed to the entrypoint. + env (MutableMapping[str, str]): + Environment variables passed to the + container's entrypoint. + working_dir (str): + If set, overrides the default DIR specified + by the image. + run_as_user (int): + If set, overrides the USER specified in the + image with the given uid. + """ + + image: str = proto.Field( + proto.STRING, + number=1, + ) + command: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + args: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + env: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + working_dir: str = proto.Field( + proto.STRING, + number=5, + ) + run_as_user: int = proto.Field( + proto.INT32, + number=6, + ) + + class CustomerEncryptionKey(proto.Message): + r"""A customer-managed encryption key for the Compute Engine + resources of this workstation configuration. + + Attributes: + kms_key (str): + Immutable. The name of the Google Cloud KMS encryption key. + For example, + ``projects/PROJECT_ID/locations/REGION/keyRings/KEY_RING/cryptoKeys/KEY_NAME``. + kms_key_service_account (str): + Immutable. The service account to use with the specified KMS + key. We recommend that you use a separate service account + and follow KMS best practices. For more information, see + `Separation of + duties `__ + and ``gcloud kms keys add-iam-policy-binding`` + ```--member`` `__. + """ + + kms_key: str = proto.Field( + proto.STRING, + number=1, + ) + kms_key_service_account: str = proto.Field( + proto.STRING, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=18, + ) + 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, + ) + idle_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=10, + message=duration_pb2.Duration, + ) + running_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=11, + message=duration_pb2.Duration, + ) + host: Host = proto.Field( + proto.MESSAGE, + number=12, + message=Host, + ) + persistent_directories: MutableSequence[PersistentDirectory] = proto.RepeatedField( + proto.MESSAGE, + number=13, + message=PersistentDirectory, + ) + container: Container = proto.Field( + proto.MESSAGE, + number=14, + message=Container, + ) + encryption_key: CustomerEncryptionKey = proto.Field( + proto.MESSAGE, + number=17, + message=CustomerEncryptionKey, + ) + degraded: bool = proto.Field( + proto.BOOL, + number=15, + ) + conditions: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=16, + message=status_pb2.Status, + ) + + +class Workstation(proto.Message): + r"""A single instance of a developer workstation with its own + persistent storage. + + Attributes: + name (str): + Full name of this resource. + display_name (str): + Human-readable name for this resource. + uid (str): + Output only. A system-assigned unique + identified for this resource. + reconciling (bool): + Output only. Indicates whether this resource + is currently being updated to match its intended + state. + annotations (MutableMapping[str, str]): + Client-specified annotations. + labels (MutableMapping[str, str]): + Client-specified labels that are applied to + the resource and that are also propagated to the + underlying Compute Engine resources. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this resource was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this resource was most + recently updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this resource was + soft-deleted. + etag (str): + Checksum computed by the server. May be sent + on update and delete requests to make sure that + the client has an up-to-date value before + proceeding. + state (google.cloud.workstations_v1.types.Workstation.State): + Output only. Current state of the + workstation. + host (str): + Output only. Host to which clients can send HTTPS traffic + that will be received by the workstation. Authorized traffic + will be received to the workstation as HTTP on port 80. To + send traffic to a different port, clients may prefix the + host with the destination port in the format + ``{port}-{host}``. + """ + class State(proto.Enum): + r"""Whether a workstation is running and ready to receive user + requests. + + Values: + STATE_UNSPECIFIED (0): + Do not use. + STATE_STARTING (1): + The workstation is not yet ready to accept + requests from users but will be soon. + STATE_RUNNING (2): + The workstation is ready to accept requests + from users. + STATE_STOPPING (3): + The workstation is being stopped. + STATE_STOPPED (4): + The workstation is stopped and will not be + able to receive requests until it is started. + """ + STATE_UNSPECIFIED = 0 + STATE_STARTING = 1 + STATE_RUNNING = 2 + STATE_STOPPING = 3 + STATE_STOPPED = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=13, + ) + 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, + ) + state: State = proto.Field( + proto.ENUM, + number=10, + enum=State, + ) + host: str = proto.Field( + proto.STRING, + number=11, + ) + + +class GetWorkstationClusterRequest(proto.Message): + r"""Request message for GetWorkstationCluster. + + Attributes: + name (str): + Required. Name of the requested resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListWorkstationClustersRequest(proto.Message): + r"""Request message for ListWorkstationClusters. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Maximum number of items to return. + page_token (str): + next_page_token value returned from a previous List request, + if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListWorkstationClustersResponse(proto.Message): + r"""Response message for ListWorkstationClusters. + + Attributes: + workstation_clusters (MutableSequence[google.cloud.workstations_v1.types.WorkstationCluster]): + The requested workstation clusters. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstation_clusters: MutableSequence['WorkstationCluster'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='WorkstationCluster', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateWorkstationClusterRequest(proto.Message): + r"""Message for creating a CreateWorkstationCluster. + + Attributes: + parent (str): + Required. Parent resource name. + workstation_cluster_id (str): + Required. ID to use for the workstation + cluster. + workstation_cluster (google.cloud.workstations_v1.types.WorkstationCluster): + Required. Workstation cluster to create. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + workstation_cluster_id: str = proto.Field( + proto.STRING, + number=2, + ) + workstation_cluster: 'WorkstationCluster' = proto.Field( + proto.MESSAGE, + number=3, + message='WorkstationCluster', + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateWorkstationClusterRequest(proto.Message): + r"""Request message for UpdateWorkstationCluster. + + Attributes: + workstation_cluster (google.cloud.workstations_v1.types.WorkstationCluster): + Required. Workstation cluster to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask that specifies which fields in + the workstation cluster should be updated. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + allow_missing (bool): + If set, and the workstation cluster is not found, a new + workstation cluster will be created. In this situation, + update_mask is ignored. + """ + + workstation_cluster: 'WorkstationCluster' = proto.Field( + proto.MESSAGE, + number=1, + message='WorkstationCluster', + ) + 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, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteWorkstationClusterRequest(proto.Message): + r"""Message for deleting a workstation cluster. + + Attributes: + name (str): + Required. Name of the workstation cluster to + delete. + validate_only (bool): + If set, validate the request and preview the + review, but do not apply it. + etag (str): + If set, the request will be rejected if the + latest version of the workstation cluster on the + server does not have this ETag. + force (bool): + If set, any workstation configurations and + workstations in the workstation cluster are also + deleted. Otherwise, the request only works if + the workstation cluster has no configurations or + workstations. + """ + + 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, + ) + force: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetWorkstationConfigRequest(proto.Message): + r"""Request message for GetWorkstationConfig. + + Attributes: + name (str): + Required. Name of the requested resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListWorkstationConfigsRequest(proto.Message): + r"""Request message for ListWorkstationConfigs. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Maximum number of items to return. + page_token (str): + next_page_token value returned from a previous List request, + if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListWorkstationConfigsResponse(proto.Message): + r"""Response message for ListWorkstationConfigs. + + Attributes: + workstation_configs (MutableSequence[google.cloud.workstations_v1.types.WorkstationConfig]): + The requested configs. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstation_configs: MutableSequence['WorkstationConfig'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='WorkstationConfig', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ListUsableWorkstationConfigsRequest(proto.Message): + r"""Request message for ListUsableWorkstationConfigs. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Maximum number of items to return. + page_token (str): + next_page_token value returned from a previous List request, + if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListUsableWorkstationConfigsResponse(proto.Message): + r"""Response message for ListUsableWorkstationConfigs. + + Attributes: + workstation_configs (MutableSequence[google.cloud.workstations_v1.types.WorkstationConfig]): + The requested configs. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstation_configs: MutableSequence['WorkstationConfig'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='WorkstationConfig', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateWorkstationConfigRequest(proto.Message): + r"""Message for creating a CreateWorkstationConfig. + + Attributes: + parent (str): + Required. Parent resource name. + workstation_config_id (str): + Required. ID to use for the workstation + configuration. + workstation_config (google.cloud.workstations_v1.types.WorkstationConfig): + Required. Config to create. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + workstation_config_id: str = proto.Field( + proto.STRING, + number=2, + ) + workstation_config: 'WorkstationConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='WorkstationConfig', + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateWorkstationConfigRequest(proto.Message): + r"""Request message for UpdateWorkstationConfig. + + Attributes: + workstation_config (google.cloud.workstations_v1.types.WorkstationConfig): + Required. Config to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask specifying which fields in the + workstation configuration should be updated. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + allow_missing (bool): + If set and the workstation configuration is not found, a new + workstation configuration will be created. In this + situation, update_mask is ignored. + """ + + workstation_config: 'WorkstationConfig' = proto.Field( + proto.MESSAGE, + number=1, + message='WorkstationConfig', + ) + 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, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteWorkstationConfigRequest(proto.Message): + r"""Message for deleting a workstation configuration. + + Attributes: + name (str): + Required. Name of the workstation + configuration to delete. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + etag (str): + If set, the request is rejected if the latest + version of the workstation configuration on the + server does not have this ETag. + force (bool): + If set, any workstations in the workstation + configuration are also deleted. Otherwise, the + request works only if the workstation + configuration has no workstations. + """ + + 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, + ) + force: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetWorkstationRequest(proto.Message): + r"""Request message for GetWorkstation. + + Attributes: + name (str): + Required. Name of the requested resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListWorkstationsRequest(proto.Message): + r"""Request message for ListWorkstations. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Maximum number of items to return. + page_token (str): + next_page_token value returned from a previous List request, + if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListWorkstationsResponse(proto.Message): + r"""Response message for ListWorkstations. + + Attributes: + workstations (MutableSequence[google.cloud.workstations_v1.types.Workstation]): + The requested workstations. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstations: MutableSequence['Workstation'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Workstation', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ListUsableWorkstationsRequest(proto.Message): + r"""Request message for ListUsableWorkstations. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Maximum number of items to return. + page_token (str): + next_page_token value returned from a previous List request, + if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListUsableWorkstationsResponse(proto.Message): + r"""Response message for ListUsableWorkstations. + + Attributes: + workstations (MutableSequence[google.cloud.workstations_v1.types.Workstation]): + The requested workstations. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstations: MutableSequence['Workstation'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Workstation', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateWorkstationRequest(proto.Message): + r"""Message for creating a CreateWorkstation. + + Attributes: + parent (str): + Required. Parent resource name. + workstation_id (str): + Required. ID to use for the workstation. + workstation (google.cloud.workstations_v1.types.Workstation): + Required. Workstation to create. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + workstation_id: str = proto.Field( + proto.STRING, + number=2, + ) + workstation: 'Workstation' = proto.Field( + proto.MESSAGE, + number=3, + message='Workstation', + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateWorkstationRequest(proto.Message): + r"""Request message for UpdateWorkstation. + + Attributes: + workstation (google.cloud.workstations_v1.types.Workstation): + Required. Workstation to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask specifying which fields in the + workstation configuration should be updated. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + allow_missing (bool): + If set and the workstation configuration is not found, a new + workstation configuration is created. In this situation, + update_mask is ignored. + """ + + workstation: 'Workstation' = proto.Field( + proto.MESSAGE, + number=1, + message='Workstation', + ) + 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, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteWorkstationRequest(proto.Message): + r"""Request message for DeleteWorkstation. + + Attributes: + name (str): + Required. Name of the workstation to delete. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + etag (str): + If set, the request will be rejected if the + latest version of the workstation on the server + does not have this ETag. + """ + + 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 StartWorkstationRequest(proto.Message): + r"""Request message for StartWorkstation. + + Attributes: + name (str): + Required. Name of the workstation to start. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + etag (str): + If set, the request will be rejected if the + latest version of the workstation on the server + does not have this ETag. + """ + + 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 StopWorkstationRequest(proto.Message): + r"""Request message for StopWorkstation. + + Attributes: + name (str): + Required. Name of the workstation to stop. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + etag (str): + If set, the request will be rejected if the + latest version of the workstation on the server + does not have this ETag. + """ + + 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 GenerateAccessTokenRequest(proto.Message): + r"""Request message for GenerateAccessToken. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Desired expiration time of the access token. + This value must be at most 24 hours in the + future. If a value is not specified, the token's + expiration time will be set to a default value + of 1 hour in the future. + + This field is a member of `oneof`_ ``expiration``. + ttl (google.protobuf.duration_pb2.Duration): + Desired lifetime duration of the access + token. This value must be at most 24 hours. If a + value is not specified, the token's lifetime + will be set to a default value of 1 hour. + + This field is a member of `oneof`_ ``expiration``. + workstation (str): + Required. Name of the workstation for which + the access token should be generated. + """ + + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + oneof='expiration', + message=timestamp_pb2.Timestamp, + ) + ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + oneof='expiration', + message=duration_pb2.Duration, + ) + workstation: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GenerateAccessTokenResponse(proto.Message): + r"""Response message for GenerateAccessToken. + + Attributes: + access_token (str): + The generated bearer access token. To use this token, + include it in an Authorization header of an HTTP request + sent to the associated workstation's hostname—for example, + ``Authorization: Bearer ``. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which the generated token will + expire. + """ + + access_token: str = proto.Field( + proto.STRING, + number=1, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class OperationMetadata(proto.Message): + r"""Metadata for long-running operations. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time that the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time that the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has + requested cancellation of the operation. + api_version (str): + Output only. API version used to start the + operation. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + status_message: str = proto.Field( + proto.STRING, + number=5, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-workstations/v1/mypy.ini b/owl-bot-staging/google-cloud-workstations/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-workstations/v1/noxfile.py b/owl-bot-staging/google-cloud-workstations/v1/noxfile.py new file mode 100644 index 000000000000..41a3c4eff40e --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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/workstations_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json new file mode 100644 index 000000000000..8dabda2a933a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json @@ -0,0 +1,3307 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.workstations.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-workstations", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.create_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.CreateWorkstationClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation_cluster", + "type": "google.cloud.workstations_v1.types.WorkstationCluster" + }, + { + "name": "workstation_cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_workstation_cluster" + }, + "description": "Sample for CreateWorkstationCluster", + "file": "workstations_v1_generated_workstations_create_workstation_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_CreateWorkstationCluster_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": "workstations_v1_generated_workstations_create_workstation_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.create_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.CreateWorkstationClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation_cluster", + "type": "google.cloud.workstations_v1.types.WorkstationCluster" + }, + { + "name": "workstation_cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_workstation_cluster" + }, + "description": "Sample for CreateWorkstationCluster", + "file": "workstations_v1_generated_workstations_create_workstation_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_CreateWorkstationCluster_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": "workstations_v1_generated_workstations_create_workstation_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.create_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.CreateWorkstationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation_config", + "type": "google.cloud.workstations_v1.types.WorkstationConfig" + }, + { + "name": "workstation_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_workstation_config" + }, + "description": "Sample for CreateWorkstationConfig", + "file": "workstations_v1_generated_workstations_create_workstation_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_CreateWorkstationConfig_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": "workstations_v1_generated_workstations_create_workstation_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.create_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.CreateWorkstationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation_config", + "type": "google.cloud.workstations_v1.types.WorkstationConfig" + }, + { + "name": "workstation_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_workstation_config" + }, + "description": "Sample for CreateWorkstationConfig", + "file": "workstations_v1_generated_workstations_create_workstation_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_CreateWorkstationConfig_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": "workstations_v1_generated_workstations_create_workstation_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.create_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.CreateWorkstationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation", + "type": "google.cloud.workstations_v1.types.Workstation" + }, + { + "name": "workstation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_workstation" + }, + "description": "Sample for CreateWorkstation", + "file": "workstations_v1_generated_workstations_create_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_CreateWorkstation_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": "workstations_v1_generated_workstations_create_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.create_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.CreateWorkstationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation", + "type": "google.cloud.workstations_v1.types.Workstation" + }, + { + "name": "workstation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_workstation" + }, + "description": "Sample for CreateWorkstation", + "file": "workstations_v1_generated_workstations_create_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_CreateWorkstation_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": "workstations_v1_generated_workstations_create_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.delete_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.DeleteWorkstationClusterRequest" + }, + { + "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_workstation_cluster" + }, + "description": "Sample for DeleteWorkstationCluster", + "file": "workstations_v1_generated_workstations_delete_workstation_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstationCluster_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": "workstations_v1_generated_workstations_delete_workstation_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.delete_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.DeleteWorkstationClusterRequest" + }, + { + "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_workstation_cluster" + }, + "description": "Sample for DeleteWorkstationCluster", + "file": "workstations_v1_generated_workstations_delete_workstation_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstationCluster_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": "workstations_v1_generated_workstations_delete_workstation_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.delete_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.DeleteWorkstationConfigRequest" + }, + { + "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_workstation_config" + }, + "description": "Sample for DeleteWorkstationConfig", + "file": "workstations_v1_generated_workstations_delete_workstation_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstationConfig_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": "workstations_v1_generated_workstations_delete_workstation_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.delete_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.DeleteWorkstationConfigRequest" + }, + { + "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_workstation_config" + }, + "description": "Sample for DeleteWorkstationConfig", + "file": "workstations_v1_generated_workstations_delete_workstation_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstationConfig_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": "workstations_v1_generated_workstations_delete_workstation_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.delete_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.DeleteWorkstationRequest" + }, + { + "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_workstation" + }, + "description": "Sample for DeleteWorkstation", + "file": "workstations_v1_generated_workstations_delete_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstation_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": "workstations_v1_generated_workstations_delete_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.delete_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.DeleteWorkstationRequest" + }, + { + "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_workstation" + }, + "description": "Sample for DeleteWorkstation", + "file": "workstations_v1_generated_workstations_delete_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstation_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": "workstations_v1_generated_workstations_delete_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.generate_access_token", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.GenerateAccessToken", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "GenerateAccessToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.GenerateAccessTokenRequest" + }, + { + "name": "workstation", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.types.GenerateAccessTokenResponse", + "shortName": "generate_access_token" + }, + "description": "Sample for GenerateAccessToken", + "file": "workstations_v1_generated_workstations_generate_access_token_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_GenerateAccessToken_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": "workstations_v1_generated_workstations_generate_access_token_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.generate_access_token", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.GenerateAccessToken", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "GenerateAccessToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.GenerateAccessTokenRequest" + }, + { + "name": "workstation", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1.types.GenerateAccessTokenResponse", + "shortName": "generate_access_token" + }, + "description": "Sample for GenerateAccessToken", + "file": "workstations_v1_generated_workstations_generate_access_token_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_GenerateAccessToken_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": "workstations_v1_generated_workstations_generate_access_token_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.get_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.GetWorkstationClusterRequest" + }, + { + "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.workstations_v1.types.WorkstationCluster", + "shortName": "get_workstation_cluster" + }, + "description": "Sample for GetWorkstationCluster", + "file": "workstations_v1_generated_workstations_get_workstation_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_GetWorkstationCluster_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": "workstations_v1_generated_workstations_get_workstation_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.get_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.GetWorkstationClusterRequest" + }, + { + "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.workstations_v1.types.WorkstationCluster", + "shortName": "get_workstation_cluster" + }, + "description": "Sample for GetWorkstationCluster", + "file": "workstations_v1_generated_workstations_get_workstation_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_GetWorkstationCluster_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": "workstations_v1_generated_workstations_get_workstation_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.get_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.GetWorkstationConfigRequest" + }, + { + "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.workstations_v1.types.WorkstationConfig", + "shortName": "get_workstation_config" + }, + "description": "Sample for GetWorkstationConfig", + "file": "workstations_v1_generated_workstations_get_workstation_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_GetWorkstationConfig_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": "workstations_v1_generated_workstations_get_workstation_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.get_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.GetWorkstationConfigRequest" + }, + { + "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.workstations_v1.types.WorkstationConfig", + "shortName": "get_workstation_config" + }, + "description": "Sample for GetWorkstationConfig", + "file": "workstations_v1_generated_workstations_get_workstation_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_GetWorkstationConfig_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": "workstations_v1_generated_workstations_get_workstation_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.get_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.GetWorkstationRequest" + }, + { + "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.workstations_v1.types.Workstation", + "shortName": "get_workstation" + }, + "description": "Sample for GetWorkstation", + "file": "workstations_v1_generated_workstations_get_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_GetWorkstation_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": "workstations_v1_generated_workstations_get_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.get_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.GetWorkstationRequest" + }, + { + "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.workstations_v1.types.Workstation", + "shortName": "get_workstation" + }, + "description": "Sample for GetWorkstation", + "file": "workstations_v1_generated_workstations_get_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_GetWorkstation_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": "workstations_v1_generated_workstations_get_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_usable_workstation_configs", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListUsableWorkstationConfigs", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListUsableWorkstationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest" + }, + { + "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.workstations_v1.services.workstations.pagers.ListUsableWorkstationConfigsAsyncPager", + "shortName": "list_usable_workstation_configs" + }, + "description": "Sample for ListUsableWorkstationConfigs", + "file": "workstations_v1_generated_workstations_list_usable_workstation_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_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": "workstations_v1_generated_workstations_list_usable_workstation_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_usable_workstation_configs", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListUsableWorkstationConfigs", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListUsableWorkstationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest" + }, + { + "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.workstations_v1.services.workstations.pagers.ListUsableWorkstationConfigsPager", + "shortName": "list_usable_workstation_configs" + }, + "description": "Sample for ListUsableWorkstationConfigs", + "file": "workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_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": "workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_usable_workstations", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListUsableWorkstations", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListUsableWorkstations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListUsableWorkstationsRequest" + }, + { + "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.workstations_v1.services.workstations.pagers.ListUsableWorkstationsAsyncPager", + "shortName": "list_usable_workstations" + }, + "description": "Sample for ListUsableWorkstations", + "file": "workstations_v1_generated_workstations_list_usable_workstations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListUsableWorkstations_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": "workstations_v1_generated_workstations_list_usable_workstations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_usable_workstations", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListUsableWorkstations", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListUsableWorkstations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListUsableWorkstationsRequest" + }, + { + "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.workstations_v1.services.workstations.pagers.ListUsableWorkstationsPager", + "shortName": "list_usable_workstations" + }, + "description": "Sample for ListUsableWorkstations", + "file": "workstations_v1_generated_workstations_list_usable_workstations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListUsableWorkstations_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": "workstations_v1_generated_workstations_list_usable_workstations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_workstation_clusters", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstationClusters", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstationClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListWorkstationClustersRequest" + }, + { + "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.workstations_v1.services.workstations.pagers.ListWorkstationClustersAsyncPager", + "shortName": "list_workstation_clusters" + }, + "description": "Sample for ListWorkstationClusters", + "file": "workstations_v1_generated_workstations_list_workstation_clusters_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListWorkstationClusters_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": "workstations_v1_generated_workstations_list_workstation_clusters_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_workstation_clusters", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstationClusters", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstationClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListWorkstationClustersRequest" + }, + { + "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.workstations_v1.services.workstations.pagers.ListWorkstationClustersPager", + "shortName": "list_workstation_clusters" + }, + "description": "Sample for ListWorkstationClusters", + "file": "workstations_v1_generated_workstations_list_workstation_clusters_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListWorkstationClusters_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": "workstations_v1_generated_workstations_list_workstation_clusters_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_workstation_configs", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstationConfigs", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListWorkstationConfigsRequest" + }, + { + "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.workstations_v1.services.workstations.pagers.ListWorkstationConfigsAsyncPager", + "shortName": "list_workstation_configs" + }, + "description": "Sample for ListWorkstationConfigs", + "file": "workstations_v1_generated_workstations_list_workstation_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListWorkstationConfigs_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": "workstations_v1_generated_workstations_list_workstation_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_workstation_configs", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstationConfigs", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListWorkstationConfigsRequest" + }, + { + "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.workstations_v1.services.workstations.pagers.ListWorkstationConfigsPager", + "shortName": "list_workstation_configs" + }, + "description": "Sample for ListWorkstationConfigs", + "file": "workstations_v1_generated_workstations_list_workstation_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListWorkstationConfigs_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": "workstations_v1_generated_workstations_list_workstation_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_workstations", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstations", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListWorkstationsRequest" + }, + { + "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.workstations_v1.services.workstations.pagers.ListWorkstationsAsyncPager", + "shortName": "list_workstations" + }, + "description": "Sample for ListWorkstations", + "file": "workstations_v1_generated_workstations_list_workstations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListWorkstations_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": "workstations_v1_generated_workstations_list_workstations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_workstations", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstations", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.ListWorkstationsRequest" + }, + { + "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.workstations_v1.services.workstations.pagers.ListWorkstationsPager", + "shortName": "list_workstations" + }, + "description": "Sample for ListWorkstations", + "file": "workstations_v1_generated_workstations_list_workstations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_ListWorkstations_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": "workstations_v1_generated_workstations_list_workstations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.start_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.StartWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "StartWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.StartWorkstationRequest" + }, + { + "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": "start_workstation" + }, + "description": "Sample for StartWorkstation", + "file": "workstations_v1_generated_workstations_start_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_StartWorkstation_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": "workstations_v1_generated_workstations_start_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.start_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.StartWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "StartWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.StartWorkstationRequest" + }, + { + "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": "start_workstation" + }, + "description": "Sample for StartWorkstation", + "file": "workstations_v1_generated_workstations_start_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_StartWorkstation_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": "workstations_v1_generated_workstations_start_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.stop_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.StopWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "StopWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.StopWorkstationRequest" + }, + { + "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": "stop_workstation" + }, + "description": "Sample for StopWorkstation", + "file": "workstations_v1_generated_workstations_stop_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_StopWorkstation_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": "workstations_v1_generated_workstations_stop_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.stop_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.StopWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "StopWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.StopWorkstationRequest" + }, + { + "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": "stop_workstation" + }, + "description": "Sample for StopWorkstation", + "file": "workstations_v1_generated_workstations_stop_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_StopWorkstation_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": "workstations_v1_generated_workstations_stop_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.update_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.UpdateWorkstationClusterRequest" + }, + { + "name": "workstation_cluster", + "type": "google.cloud.workstations_v1.types.WorkstationCluster" + }, + { + "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_workstation_cluster" + }, + "description": "Sample for UpdateWorkstationCluster", + "file": "workstations_v1_generated_workstations_update_workstation_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstationCluster_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": "workstations_v1_generated_workstations_update_workstation_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.update_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.UpdateWorkstationClusterRequest" + }, + { + "name": "workstation_cluster", + "type": "google.cloud.workstations_v1.types.WorkstationCluster" + }, + { + "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_workstation_cluster" + }, + "description": "Sample for UpdateWorkstationCluster", + "file": "workstations_v1_generated_workstations_update_workstation_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstationCluster_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": "workstations_v1_generated_workstations_update_workstation_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.update_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.UpdateWorkstationConfigRequest" + }, + { + "name": "workstation_config", + "type": "google.cloud.workstations_v1.types.WorkstationConfig" + }, + { + "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_workstation_config" + }, + "description": "Sample for UpdateWorkstationConfig", + "file": "workstations_v1_generated_workstations_update_workstation_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstationConfig_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": "workstations_v1_generated_workstations_update_workstation_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.update_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.UpdateWorkstationConfigRequest" + }, + { + "name": "workstation_config", + "type": "google.cloud.workstations_v1.types.WorkstationConfig" + }, + { + "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_workstation_config" + }, + "description": "Sample for UpdateWorkstationConfig", + "file": "workstations_v1_generated_workstations_update_workstation_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstationConfig_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": "workstations_v1_generated_workstations_update_workstation_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.update_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.UpdateWorkstationRequest" + }, + { + "name": "workstation", + "type": "google.cloud.workstations_v1.types.Workstation" + }, + { + "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_workstation" + }, + "description": "Sample for UpdateWorkstation", + "file": "workstations_v1_generated_workstations_update_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstation_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": "workstations_v1_generated_workstations_update_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1.WorkstationsClient.update_workstation", + "method": { + "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1.types.UpdateWorkstationRequest" + }, + { + "name": "workstation", + "type": "google.cloud.workstations_v1.types.Workstation" + }, + { + "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_workstation" + }, + "description": "Sample for UpdateWorkstation", + "file": "workstations_v1_generated_workstations_update_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstation_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": "workstations_v1_generated_workstations_update_workstation_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_async.py new file mode 100644 index 000000000000..89a8344d0ea6 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_CreateWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_create_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationRequest( + parent="parent_value", + workstation_id="workstation_id_value", + ) + + # Make the request + operation = client.create_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_CreateWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_async.py new file mode 100644 index 000000000000..d27a68364a39 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_CreateWorkstationCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_create_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationClusterRequest( + parent="parent_value", + workstation_cluster_id="workstation_cluster_id_value", + ) + + # Make the request + operation = client.create_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_CreateWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_sync.py new file mode 100644 index 000000000000..cac2a6b31678 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_CreateWorkstationCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_create_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationClusterRequest( + parent="parent_value", + workstation_cluster_id="workstation_cluster_id_value", + ) + + # Make the request + operation = client.create_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_CreateWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_async.py new file mode 100644 index 000000000000..d84606878316 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_CreateWorkstationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_create_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationConfigRequest( + parent="parent_value", + workstation_config_id="workstation_config_id_value", + ) + + # Make the request + operation = client.create_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_CreateWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_sync.py new file mode 100644 index 000000000000..2793998a735b --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_CreateWorkstationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_create_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationConfigRequest( + parent="parent_value", + workstation_config_id="workstation_config_id_value", + ) + + # Make the request + operation = client.create_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_CreateWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_sync.py new file mode 100644 index 000000000000..0f5fc372cb1a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_CreateWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_create_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.CreateWorkstationRequest( + parent="parent_value", + workstation_id="workstation_id_value", + ) + + # Make the request + operation = client.create_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_CreateWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_async.py new file mode 100644 index 000000000000..7cef6fd6f42f --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_DeleteWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_delete_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_DeleteWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_async.py new file mode 100644 index 000000000000..6f5c9cf4e567 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_DeleteWorkstationCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_delete_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_DeleteWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_sync.py new file mode 100644 index 000000000000..bdc26bc6599e --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_DeleteWorkstationCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_delete_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_DeleteWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_async.py new file mode 100644 index 000000000000..1954a3d63121 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_DeleteWorkstationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_delete_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_DeleteWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_sync.py new file mode 100644 index 000000000000..0883ac378b5a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_DeleteWorkstationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_delete_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_DeleteWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_sync.py new file mode 100644 index 000000000000..96be92bcf338 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_DeleteWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_delete_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.DeleteWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_DeleteWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_async.py new file mode 100644 index 000000000000..7c38f6f86ce9 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateAccessToken +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_GenerateAccessToken_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_generate_access_token(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.GenerateAccessTokenRequest( + workstation="workstation_value", + ) + + # Make the request + response = await client.generate_access_token(request=request) + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_GenerateAccessToken_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_sync.py new file mode 100644 index 000000000000..872470075a79 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateAccessToken +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_GenerateAccessToken_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_generate_access_token(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.GenerateAccessTokenRequest( + workstation="workstation_value", + ) + + # Make the request + response = client.generate_access_token(request=request) + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_GenerateAccessToken_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_async.py new file mode 100644 index 000000000000..6a893b9d9dc7 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_GetWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_get_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation(request=request) + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_GetWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_async.py new file mode 100644 index 000000000000..b989470d3f42 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_GetWorkstationCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_get_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation_cluster(request=request) + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_GetWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_sync.py new file mode 100644 index 000000000000..ae396a9e7538 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_GetWorkstationCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_get_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation_cluster(request=request) + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_GetWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_async.py new file mode 100644 index 000000000000..585e7e653b43 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_GetWorkstationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_get_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation_config(request=request) + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_GetWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_sync.py new file mode 100644 index 000000000000..31226bc5c8b8 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_GetWorkstationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_get_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation_config(request=request) + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_GetWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_sync.py new file mode 100644 index 000000000000..e5fc47e62da5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_GetWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_get_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.GetWorkstationRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation(request=request) + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_GetWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_async.py new file mode 100644 index 000000000000..d4a502988bd7 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUsableWorkstationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_list_usable_workstation_configs(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListUsableWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstation_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py new file mode 100644 index 000000000000..dbc338eb4b89 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUsableWorkstationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_list_usable_workstation_configs(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListUsableWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstation_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_async.py new file mode 100644 index 000000000000..89020a9b2551 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUsableWorkstations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListUsableWorkstations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_list_usable_workstations(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListUsableWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListUsableWorkstations_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_sync.py new file mode 100644 index 000000000000..33e592f08dc2 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUsableWorkstations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListUsableWorkstations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_list_usable_workstations(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListUsableWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListUsableWorkstations_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_async.py new file mode 100644 index 000000000000..5b819c9660a2 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListWorkstationClusters +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListWorkstationClusters_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_list_workstation_clusters(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListWorkstationClusters_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_sync.py new file mode 100644 index 000000000000..b5ae979380d8 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListWorkstationClusters +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListWorkstationClusters_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_list_workstation_clusters(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListWorkstationClusters_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_async.py new file mode 100644 index 000000000000..9254e3a40e17 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListWorkstationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListWorkstationConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_list_workstation_configs(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListWorkstationConfigs_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_sync.py new file mode 100644 index 000000000000..855946d5d01d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListWorkstationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListWorkstationConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_list_workstation_configs(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListWorkstationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_async.py new file mode 100644 index 000000000000..b958d7af6e06 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListWorkstations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListWorkstations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_list_workstations(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListWorkstations_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_sync.py new file mode 100644 index 000000000000..5fb7c29d70e6 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListWorkstations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_ListWorkstations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_list_workstations(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.ListWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1_generated_Workstations_ListWorkstations_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_async.py new file mode 100644 index 000000000000..f58aa3ede984 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StartWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_StartWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_start_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.StartWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.start_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_StartWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_sync.py new file mode 100644 index 000000000000..3cfeee47342b --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StartWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_StartWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_start_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.StartWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.start_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_StartWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_async.py new file mode 100644 index 000000000000..080617e3ee48 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StopWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_StopWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_stop_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.StopWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_StopWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_sync.py new file mode 100644 index 000000000000..bd811dc972f5 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StopWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_StopWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_stop_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.StopWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_StopWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_async.py new file mode 100644 index 000000000000..12a7cc9fa3a3 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_UpdateWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_update_workstation(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationRequest( + ) + + # Make the request + operation = client.update_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_UpdateWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_async.py new file mode 100644 index 000000000000..b635ef7d3369 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_UpdateWorkstationCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_update_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationClusterRequest( + ) + + # Make the request + operation = client.update_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_UpdateWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_sync.py new file mode 100644 index 000000000000..7d0418825c0a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_UpdateWorkstationCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_update_workstation_cluster(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationClusterRequest( + ) + + # Make the request + operation = client.update_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_UpdateWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_async.py new file mode 100644 index 000000000000..d2f99b937d22 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_UpdateWorkstationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +async def sample_update_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationConfigRequest( + ) + + # Make the request + operation = client.update_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_UpdateWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_sync.py new file mode 100644 index 000000000000..93fde4da6273 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_UpdateWorkstationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_update_workstation_config(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationConfigRequest( + ) + + # Make the request + operation = client.update_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_UpdateWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_sync.py new file mode 100644 index 000000000000..23796c1a85db --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1_generated_Workstations_UpdateWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1 + + +def sample_update_workstation(): + # Create a client + client = workstations_v1.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1.UpdateWorkstationRequest( + ) + + # Make the request + operation = client.update_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1_generated_Workstations_UpdateWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/scripts/fixup_workstations_v1_keywords.py b/owl-bot-staging/google-cloud-workstations/v1/scripts/fixup_workstations_v1_keywords.py new file mode 100644 index 000000000000..4f7ba7cb1e17 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/scripts/fixup_workstations_v1_keywords.py @@ -0,0 +1,195 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 workstationsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_workstation': ('parent', 'workstation_id', 'workstation', 'validate_only', ), + 'create_workstation_cluster': ('parent', 'workstation_cluster_id', 'workstation_cluster', 'validate_only', ), + 'create_workstation_config': ('parent', 'workstation_config_id', 'workstation_config', 'validate_only', ), + 'delete_workstation': ('name', 'validate_only', 'etag', ), + 'delete_workstation_cluster': ('name', 'validate_only', 'etag', 'force', ), + 'delete_workstation_config': ('name', 'validate_only', 'etag', 'force', ), + 'generate_access_token': ('workstation', 'expire_time', 'ttl', ), + 'get_workstation': ('name', ), + 'get_workstation_cluster': ('name', ), + 'get_workstation_config': ('name', ), + 'list_usable_workstation_configs': ('parent', 'page_size', 'page_token', ), + 'list_usable_workstations': ('parent', 'page_size', 'page_token', ), + 'list_workstation_clusters': ('parent', 'page_size', 'page_token', ), + 'list_workstation_configs': ('parent', 'page_size', 'page_token', ), + 'list_workstations': ('parent', 'page_size', 'page_token', ), + 'start_workstation': ('name', 'validate_only', 'etag', ), + 'stop_workstation': ('name', 'validate_only', 'etag', ), + 'update_workstation': ('workstation', 'update_mask', 'validate_only', 'allow_missing', ), + 'update_workstation_cluster': ('workstation_cluster', 'update_mask', 'validate_only', 'allow_missing', ), + 'update_workstation_config': ('workstation_config', 'update_mask', 'validate_only', 'allow_missing', ), + } + + 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=workstationsCallTransformer(), +): + """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 workstations client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-workstations/v1/setup.py b/owl-bot-staging/google-cloud-workstations/v1/setup.py new file mode 100644 index 000000000000..1483952d60ff --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/setup.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-workstations' + + +description = "Google Cloud Workstations API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/workstations/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-workstations" + +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/google-cloud-workstations/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..2beecf99e0be --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 +grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/tests/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/tests/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-workstations/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/test_workstations.py b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/test_workstations.py new file mode 100644 index 000000000000..cbb58219b309 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/test_workstations.py @@ -0,0 +1,13498 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.location import locations_pb2 +from google.cloud.workstations_v1.services.workstations import WorkstationsAsyncClient +from google.cloud.workstations_v1.services.workstations import WorkstationsClient +from google.cloud.workstations_v1.services.workstations import pagers +from google.cloud.workstations_v1.services.workstations import transports +from google.cloud.workstations_v1.types import workstations +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 any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_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 WorkstationsClient._get_default_mtls_endpoint(None) is None + assert WorkstationsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert WorkstationsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert WorkstationsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert WorkstationsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert WorkstationsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (WorkstationsClient, "grpc"), + (WorkstationsAsyncClient, "grpc_asyncio"), + (WorkstationsClient, "rest"), +]) +def test_workstations_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 == ( + 'workstations.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://workstations.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.WorkstationsGrpcTransport, "grpc"), + (transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.WorkstationsRestTransport, "rest"), +]) +def test_workstations_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", [ + (WorkstationsClient, "grpc"), + (WorkstationsAsyncClient, "grpc_asyncio"), + (WorkstationsClient, "rest"), +]) +def test_workstations_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 == ( + 'workstations.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://workstations.googleapis.com' + ) + + +def test_workstations_client_get_transport_class(): + transport = WorkstationsClient.get_transport_class() + available_transports = [ + transports.WorkstationsGrpcTransport, + transports.WorkstationsRestTransport, + ] + assert transport in available_transports + + transport = WorkstationsClient.get_transport_class("grpc") + assert transport == transports.WorkstationsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), +]) +@mock.patch.object(WorkstationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsClient)) +@mock.patch.object(WorkstationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsAsyncClient)) +def test_workstations_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(WorkstationsClient, '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(WorkstationsClient, '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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", "true"), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", "false"), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest", "true"), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest", "false"), +]) +@mock.patch.object(WorkstationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsClient)) +@mock.patch.object(WorkstationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_workstations_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", [ + WorkstationsClient, WorkstationsAsyncClient +]) +@mock.patch.object(WorkstationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsClient)) +@mock.patch.object(WorkstationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsAsyncClient)) +def test_workstations_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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), +]) +def test_workstations_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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", grpc_helpers), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest", None), +]) +def test_workstations_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_workstations_client_client_options_from_dict(): + with mock.patch('google.cloud.workstations_v1.services.workstations.transports.WorkstationsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = WorkstationsClient( + 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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", grpc_helpers), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_workstations_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( + "workstations.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="workstations.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationClusterRequest, + dict, +]) +def test_get_workstation_cluster(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationCluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + network='network_value', + subnetwork='subnetwork_value', + control_plane_ip='control_plane_ip_value', + degraded=True, + ) + response = client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationCluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.network == 'network_value' + assert response.subnetwork == 'subnetwork_value' + assert response.control_plane_ip == 'control_plane_ip_value' + assert response.degraded is True + + +def test_get_workstation_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_cluster), + '__call__') as call: + client.get_workstation_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationClusterRequest() + +@pytest.mark.asyncio +async def test_get_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationClusterRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + network='network_value', + subnetwork='subnetwork_value', + control_plane_ip='control_plane_ip_value', + degraded=True, + )) + response = await client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationCluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.network == 'network_value' + assert response.subnetwork == 'subnetwork_value' + assert response.control_plane_ip == 'control_plane_ip_value' + assert response.degraded is True + + +@pytest.mark.asyncio +async def test_get_workstation_cluster_async_from_dict(): + await test_get_workstation_cluster_async(request_type=dict) + + +def test_get_workstation_cluster_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + call.return_value = workstations.WorkstationCluster() + client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster()) + await client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationCluster() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_workstation_cluster( + 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_workstation_cluster_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_cluster( + workstations.GetWorkstationClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_workstation_cluster_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationCluster() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_workstation_cluster( + 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_workstation_cluster_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_cluster( + workstations.GetWorkstationClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationClustersRequest, + dict, +]) +def test_list_workstation_clusters(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationClustersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationClustersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workstation_clusters_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_clusters), + '__call__') as call: + client.list_workstation_clusters() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationClustersRequest() + +@pytest.mark.asyncio +async def test_list_workstation_clusters_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationClustersRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationClustersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationClustersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_workstation_clusters_async_from_dict(): + await test_list_workstation_clusters_async(request_type=dict) + + +def test_list_workstation_clusters_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + call.return_value = workstations.ListWorkstationClustersResponse() + client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_workstation_clusters_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse()) + await client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_workstation_clusters_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationClustersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_workstation_clusters( + 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_workstation_clusters_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_clusters( + workstations.ListWorkstationClustersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_workstation_clusters_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationClustersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_workstation_clusters( + 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_workstation_clusters_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_clusters( + workstations.ListWorkstationClustersRequest(), + parent='parent_value', + ) + + +def test_list_workstation_clusters_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstation_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_workstation_clusters(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.WorkstationCluster) + for i in results) +def test_list_workstation_clusters_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstation_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + RuntimeError, + ) + pages = list(client.list_workstation_clusters(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_workstation_clusters_async_pager(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_workstation_clusters(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, workstations.WorkstationCluster) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_workstation_clusters_async_pages(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_workstation_clusters(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + workstations.CreateWorkstationClusterRequest, + dict, +]) +def test_create_workstation_cluster(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_workstation_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_cluster), + '__call__') as call: + client.create_workstation_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationClusterRequest() + +@pytest.mark.asyncio +async def test_create_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationClusterRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__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_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_workstation_cluster_async_from_dict(): + await test_create_workstation_cluster_async(request_type=dict) + + +def test_create_workstation_cluster_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_workstation_cluster_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_workstation_cluster_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__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_workstation_cluster( + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].workstation_cluster + mock_val = workstations.WorkstationCluster(name='name_value') + assert arg == mock_val + arg = args[0].workstation_cluster_id + mock_val = 'workstation_cluster_id_value' + assert arg == mock_val + + +def test_create_workstation_cluster_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_cluster( + workstations.CreateWorkstationClusterRequest(), + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_value', + ) + +@pytest.mark.asyncio +async def test_create_workstation_cluster_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__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_workstation_cluster( + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].workstation_cluster + mock_val = workstations.WorkstationCluster(name='name_value') + assert arg == mock_val + arg = args[0].workstation_cluster_id + mock_val = 'workstation_cluster_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_workstation_cluster_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_cluster( + workstations.CreateWorkstationClusterRequest(), + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationClusterRequest, + dict, +]) +def test_update_workstation_cluster(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_workstation_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_cluster), + '__call__') as call: + client.update_workstation_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationClusterRequest() + +@pytest.mark.asyncio +async def test_update_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationClusterRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__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_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_workstation_cluster_async_from_dict(): + await test_update_workstation_cluster_async(request_type=dict) + + +def test_update_workstation_cluster_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationClusterRequest() + + request.workstation_cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation_cluster.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_workstation_cluster_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationClusterRequest() + + request.workstation_cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation_cluster.name=name_value', + ) in kw['metadata'] + + +def test_update_workstation_cluster_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__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_workstation_cluster( + workstation_cluster=workstations.WorkstationCluster(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].workstation_cluster + mock_val = workstations.WorkstationCluster(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_workstation_cluster_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_cluster( + workstations.UpdateWorkstationClusterRequest(), + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_workstation_cluster_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__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_workstation_cluster( + workstation_cluster=workstations.WorkstationCluster(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].workstation_cluster + mock_val = workstations.WorkstationCluster(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_workstation_cluster_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_cluster( + workstations.UpdateWorkstationClusterRequest(), + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationClusterRequest, + dict, +]) +def test_delete_workstation_cluster(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_workstation_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_cluster), + '__call__') as call: + client.delete_workstation_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationClusterRequest() + +@pytest.mark.asyncio +async def test_delete_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationClusterRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__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_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_workstation_cluster_async_from_dict(): + await test_delete_workstation_cluster_async(request_type=dict) + + +def test_delete_workstation_cluster_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__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_workstation_cluster( + 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_workstation_cluster_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_cluster( + workstations.DeleteWorkstationClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_workstation_cluster_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__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_workstation_cluster( + 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_workstation_cluster_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_cluster( + workstations.DeleteWorkstationClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationConfigRequest, + dict, +]) +def test_get_workstation_config(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationConfig( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + degraded=True, + ) + response = client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.degraded is True + + +def test_get_workstation_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_config), + '__call__') as call: + client.get_workstation_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationConfigRequest() + +@pytest.mark.asyncio +async def test_get_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationConfigRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + degraded=True, + )) + response = await client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.degraded is True + + +@pytest.mark.asyncio +async def test_get_workstation_config_async_from_dict(): + await test_get_workstation_config_async(request_type=dict) + + +def test_get_workstation_config_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + call.return_value = workstations.WorkstationConfig() + client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_workstation_config_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig()) + await client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_workstation_config_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_workstation_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_workstation_config_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_config( + workstations.GetWorkstationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_workstation_config_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_workstation_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_workstation_config_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_config( + workstations.GetWorkstationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationConfigsRequest, + dict, +]) +def test_list_workstation_configs(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workstation_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_configs), + '__call__') as call: + client.list_workstation_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationConfigsRequest() + +@pytest.mark.asyncio +async def test_list_workstation_configs_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationConfigsRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_workstation_configs_async_from_dict(): + await test_list_workstation_configs_async(request_type=dict) + + +def test_list_workstation_configs_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + call.return_value = workstations.ListWorkstationConfigsResponse() + client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_workstation_configs_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse()) + await client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_workstation_configs_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_workstation_configs( + 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_workstation_configs_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_configs( + workstations.ListWorkstationConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_workstation_configs_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_workstation_configs( + 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_workstation_configs_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_configs( + workstations.ListWorkstationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_workstation_configs_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstation_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_workstation_configs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.WorkstationConfig) + for i in results) +def test_list_workstation_configs_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstation_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_workstation_configs(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_workstation_configs_async_pager(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_workstation_configs(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, workstations.WorkstationConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_workstation_configs_async_pages(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_workstation_configs(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + workstations.ListUsableWorkstationConfigsRequest, + dict, +]) +def test_list_usable_workstation_configs(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_usable_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListUsableWorkstationConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_usable_workstation_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_usable_workstation_configs), + '__call__') as call: + client.list_usable_workstation_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListUsableWorkstationConfigsRequest() + +@pytest.mark.asyncio +async def test_list_usable_workstation_configs_async(transport: str = 'grpc_asyncio', request_type=workstations.ListUsableWorkstationConfigsRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_usable_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListUsableWorkstationConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_usable_workstation_configs_async_from_dict(): + await test_list_usable_workstation_configs_async(request_type=dict) + + +def test_list_usable_workstation_configs_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListUsableWorkstationConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + call.return_value = workstations.ListUsableWorkstationConfigsResponse() + client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_usable_workstation_configs_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListUsableWorkstationConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse()) + await client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_usable_workstation_configs_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_usable_workstation_configs( + 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_usable_workstation_configs_flattened_error(): + client = WorkstationsClient( + credentials=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_usable_workstation_configs( + workstations.ListUsableWorkstationConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_usable_workstation_configs_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_usable_workstation_configs( + 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_usable_workstation_configs_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_usable_workstation_configs( + workstations.ListUsableWorkstationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_usable_workstation_configs_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_usable_workstation_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_usable_workstation_configs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.WorkstationConfig) + for i in results) +def test_list_usable_workstation_configs_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_usable_workstation_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_usable_workstation_configs(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_usable_workstation_configs_async_pager(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_usable_workstation_configs(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, workstations.WorkstationConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_usable_workstation_configs_async_pages(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_usable_workstation_configs(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + workstations.CreateWorkstationConfigRequest, + dict, +]) +def test_create_workstation_config(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_workstation_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_config), + '__call__') as call: + client.create_workstation_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationConfigRequest() + +@pytest.mark.asyncio +async def test_create_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationConfigRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__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_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_workstation_config_async_from_dict(): + await test_create_workstation_config_async(request_type=dict) + + +def test_create_workstation_config_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_workstation_config_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_workstation_config_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__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_workstation_config( + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].workstation_config + mock_val = workstations.WorkstationConfig(name='name_value') + assert arg == mock_val + arg = args[0].workstation_config_id + mock_val = 'workstation_config_id_value' + assert arg == mock_val + + +def test_create_workstation_config_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_config( + workstations.CreateWorkstationConfigRequest(), + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_value', + ) + +@pytest.mark.asyncio +async def test_create_workstation_config_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__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_workstation_config( + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].workstation_config + mock_val = workstations.WorkstationConfig(name='name_value') + assert arg == mock_val + arg = args[0].workstation_config_id + mock_val = 'workstation_config_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_workstation_config_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_config( + workstations.CreateWorkstationConfigRequest(), + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationConfigRequest, + dict, +]) +def test_update_workstation_config(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_workstation_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_config), + '__call__') as call: + client.update_workstation_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationConfigRequest() + +@pytest.mark.asyncio +async def test_update_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationConfigRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__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_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_workstation_config_async_from_dict(): + await test_update_workstation_config_async(request_type=dict) + + +def test_update_workstation_config_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationConfigRequest() + + request.workstation_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_workstation_config_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationConfigRequest() + + request.workstation_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation_config.name=name_value', + ) in kw['metadata'] + + +def test_update_workstation_config_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__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_workstation_config( + workstation_config=workstations.WorkstationConfig(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].workstation_config + mock_val = workstations.WorkstationConfig(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_workstation_config_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_config( + workstations.UpdateWorkstationConfigRequest(), + workstation_config=workstations.WorkstationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_workstation_config_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__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_workstation_config( + workstation_config=workstations.WorkstationConfig(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].workstation_config + mock_val = workstations.WorkstationConfig(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_workstation_config_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_config( + workstations.UpdateWorkstationConfigRequest(), + workstation_config=workstations.WorkstationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationConfigRequest, + dict, +]) +def test_delete_workstation_config(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_workstation_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_config), + '__call__') as call: + client.delete_workstation_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationConfigRequest() + +@pytest.mark.asyncio +async def test_delete_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationConfigRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__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_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_workstation_config_async_from_dict(): + await test_delete_workstation_config_async(request_type=dict) + + +def test_delete_workstation_config_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_workstation_config_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_workstation_config_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__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_workstation_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_workstation_config_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_config( + workstations.DeleteWorkstationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_workstation_config_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__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_workstation_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_workstation_config_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_config( + workstations.DeleteWorkstationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationRequest, + dict, +]) +def test_get_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.Workstation( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + state=workstations.Workstation.State.STATE_STARTING, + host='host_value', + ) + response = client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.Workstation) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.state == workstations.Workstation.State.STATE_STARTING + assert response.host == 'host_value' + + +def test_get_workstation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation), + '__call__') as call: + client.get_workstation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationRequest() + +@pytest.mark.asyncio +async def test_get_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + state=workstations.Workstation.State.STATE_STARTING, + host='host_value', + )) + response = await client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.Workstation) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.state == workstations.Workstation.State.STATE_STARTING + assert response.host == 'host_value' + + +@pytest.mark.asyncio +async def test_get_workstation_async_from_dict(): + await test_get_workstation_async(request_type=dict) + + +def test_get_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + call.return_value = workstations.Workstation() + client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation()) + await client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.Workstation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_workstation( + 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_workstation_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation( + workstations.GetWorkstationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.Workstation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_workstation( + 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_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation( + workstations.GetWorkstationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationsRequest, + dict, +]) +def test_list_workstations(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workstations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstations), + '__call__') as call: + client.list_workstations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationsRequest() + +@pytest.mark.asyncio +async def test_list_workstations_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationsRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_workstations_async_from_dict(): + await test_list_workstations_async(request_type=dict) + + +def test_list_workstations_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + call.return_value = workstations.ListWorkstationsResponse() + client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_workstations_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse()) + await client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_workstations_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_workstations( + 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_workstations_flattened_error(): + client = WorkstationsClient( + credentials=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_workstations( + workstations.ListWorkstationsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_workstations_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_workstations( + 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_workstations_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstations( + workstations.ListWorkstationsRequest(), + parent='parent_value', + ) + + +def test_list_workstations_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_workstations(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.Workstation) + for i in results) +def test_list_workstations_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_workstations(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_workstations_async_pager(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_workstations(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, workstations.Workstation) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_workstations_async_pages(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_workstations(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + workstations.ListUsableWorkstationsRequest, + dict, +]) +def test_list_usable_workstations(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_usable_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListUsableWorkstationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_usable_workstations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_usable_workstations), + '__call__') as call: + client.list_usable_workstations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListUsableWorkstationsRequest() + +@pytest.mark.asyncio +async def test_list_usable_workstations_async(transport: str = 'grpc_asyncio', request_type=workstations.ListUsableWorkstationsRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_usable_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListUsableWorkstationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_usable_workstations_async_from_dict(): + await test_list_usable_workstations_async(request_type=dict) + + +def test_list_usable_workstations_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListUsableWorkstationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + call.return_value = workstations.ListUsableWorkstationsResponse() + client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_usable_workstations_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListUsableWorkstationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse()) + await client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_usable_workstations_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_usable_workstations( + 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_usable_workstations_flattened_error(): + client = WorkstationsClient( + credentials=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_usable_workstations( + workstations.ListUsableWorkstationsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_usable_workstations_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_usable_workstations( + 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_usable_workstations_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_usable_workstations( + workstations.ListUsableWorkstationsRequest(), + parent='parent_value', + ) + + +def test_list_usable_workstations_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_usable_workstations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_usable_workstations(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.Workstation) + for i in results) +def test_list_usable_workstations_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_usable_workstations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_usable_workstations(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_usable_workstations_async_pager(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_usable_workstations(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, workstations.Workstation) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_usable_workstations_async_pages(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_usable_workstations(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + workstations.CreateWorkstationRequest, + dict, +]) +def test_create_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_workstation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation), + '__call__') as call: + client.create_workstation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationRequest() + +@pytest.mark.asyncio +async def test_create_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__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_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_workstation_async_from_dict(): + await test_create_workstation_async(request_type=dict) + + +def test_create_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__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_workstation( + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].workstation + mock_val = workstations.Workstation(name='name_value') + assert arg == mock_val + arg = args[0].workstation_id + mock_val = 'workstation_id_value' + assert arg == mock_val + + +def test_create_workstation_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation( + workstations.CreateWorkstationRequest(), + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_value', + ) + +@pytest.mark.asyncio +async def test_create_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__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_workstation( + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].workstation + mock_val = workstations.Workstation(name='name_value') + assert arg == mock_val + arg = args[0].workstation_id + mock_val = 'workstation_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation( + workstations.CreateWorkstationRequest(), + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationRequest, + dict, +]) +def test_update_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_workstation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation), + '__call__') as call: + client.update_workstation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationRequest() + +@pytest.mark.asyncio +async def test_update_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__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_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_workstation_async_from_dict(): + await test_update_workstation_async(request_type=dict) + + +def test_update_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationRequest() + + request.workstation.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationRequest() + + request.workstation.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation.name=name_value', + ) in kw['metadata'] + + +def test_update_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__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_workstation( + workstation=workstations.Workstation(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].workstation + mock_val = workstations.Workstation(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_workstation_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation( + workstations.UpdateWorkstationRequest(), + workstation=workstations.Workstation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__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_workstation( + workstation=workstations.Workstation(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].workstation + mock_val = workstations.Workstation(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_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation( + workstations.UpdateWorkstationRequest(), + workstation=workstations.Workstation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationRequest, + dict, +]) +def test_delete_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_workstation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation), + '__call__') as call: + client.delete_workstation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationRequest() + +@pytest.mark.asyncio +async def test_delete_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__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_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_workstation_async_from_dict(): + await test_delete_workstation_async(request_type=dict) + + +def test_delete_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__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_workstation( + 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_workstation_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation( + workstations.DeleteWorkstationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__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_workstation( + 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_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation( + workstations.DeleteWorkstationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.StartWorkstationRequest, + dict, +]) +def test_start_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.start_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.StartWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_start_workstation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + client.start_workstation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.StartWorkstationRequest() + +@pytest.mark.asyncio +async def test_start_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.StartWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__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.start_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.StartWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_start_workstation_async_from_dict(): + await test_start_workstation_async(request_type=dict) + + +def test_start_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.StartWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.start_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_start_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.StartWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.start_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_start_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__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.start_workstation( + 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_start_workstation_flattened_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.start_workstation( + workstations.StartWorkstationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_start_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__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.start_workstation( + 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_start_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + 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.start_workstation( + workstations.StartWorkstationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.StopWorkstationRequest, + dict, +]) +def test_stop_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.stop_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.StopWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_stop_workstation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + client.stop_workstation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.StopWorkstationRequest() + +@pytest.mark.asyncio +async def test_stop_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.StopWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__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.stop_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.StopWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_stop_workstation_async_from_dict(): + await test_stop_workstation_async(request_type=dict) + + +def test_stop_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.StopWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.stop_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_stop_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.StopWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.stop_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_stop_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__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.stop_workstation( + 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_stop_workstation_flattened_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.stop_workstation( + workstations.StopWorkstationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_stop_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__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.stop_workstation( + 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_stop_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + 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.stop_workstation( + workstations.StopWorkstationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GenerateAccessTokenRequest, + dict, +]) +def test_generate_access_token(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.GenerateAccessTokenResponse( + access_token='access_token_value', + ) + response = client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GenerateAccessTokenRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.GenerateAccessTokenResponse) + assert response.access_token == 'access_token_value' + + +def test_generate_access_token_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + client.generate_access_token() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GenerateAccessTokenRequest() + +@pytest.mark.asyncio +async def test_generate_access_token_async(transport: str = 'grpc_asyncio', request_type=workstations.GenerateAccessTokenRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse( + access_token='access_token_value', + )) + response = await client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GenerateAccessTokenRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.GenerateAccessTokenResponse) + assert response.access_token == 'access_token_value' + + +@pytest.mark.asyncio +async def test_generate_access_token_async_from_dict(): + await test_generate_access_token_async(request_type=dict) + + +def test_generate_access_token_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GenerateAccessTokenRequest() + + request.workstation = 'workstation_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + call.return_value = workstations.GenerateAccessTokenResponse() + client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation=workstation_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_generate_access_token_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GenerateAccessTokenRequest() + + request.workstation = 'workstation_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse()) + await client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation=workstation_value', + ) in kw['metadata'] + + +def test_generate_access_token_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.GenerateAccessTokenResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.generate_access_token( + workstation='workstation_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].workstation + mock_val = 'workstation_value' + assert arg == mock_val + + +def test_generate_access_token_flattened_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_access_token( + workstations.GenerateAccessTokenRequest(), + workstation='workstation_value', + ) + +@pytest.mark.asyncio +async def test_generate_access_token_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.GenerateAccessTokenResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.generate_access_token( + workstation='workstation_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].workstation + mock_val = 'workstation_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_generate_access_token_flattened_error_async(): + client = WorkstationsAsyncClient( + 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.generate_access_token( + workstations.GenerateAccessTokenRequest(), + workstation='workstation_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationClusterRequest, + dict, +]) +def test_get_workstation_cluster_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationCluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + network='network_value', + subnetwork='subnetwork_value', + control_plane_ip='control_plane_ip_value', + degraded=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.WorkstationCluster.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_workstation_cluster(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationCluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.network == 'network_value' + assert response.subnetwork == 'subnetwork_value' + assert response.control_plane_ip == 'control_plane_ip_value' + assert response.degraded is True + + +def test_get_workstation_cluster_rest_required_fields(request_type=workstations.GetWorkstationClusterRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_cluster._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_workstation_cluster._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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationCluster() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # 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 = workstations.WorkstationCluster.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_workstation_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_workstation_cluster_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_workstation_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_workstation_cluster_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation_cluster") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.GetWorkstationClusterRequest.pb(workstations.GetWorkstationClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = workstations.WorkstationCluster.to_json(workstations.WorkstationCluster()) + + request = workstations.GetWorkstationClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.WorkstationCluster() + + client.get_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_workstation_cluster_rest_bad_request(transport: str = 'rest', request_type=workstations.GetWorkstationClusterRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_workstation_cluster(request) + + +def test_get_workstation_cluster_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationCluster() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.WorkstationCluster.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_workstation_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) + + +def test_get_workstation_cluster_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_cluster( + workstations.GetWorkstationClusterRequest(), + name='name_value', + ) + + +def test_get_workstation_cluster_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationClustersRequest, + dict, +]) +def test_list_workstation_clusters_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListWorkstationClustersResponse.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_workstation_clusters(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationClustersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workstation_clusters_rest_required_fields(request_type=workstations.ListWorkstationClustersRequest): + transport_class = transports.WorkstationsRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstation_clusters._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstation_clusters._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationClustersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # 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 = workstations.ListWorkstationClustersResponse.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_workstation_clusters(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_workstation_clusters_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_workstation_clusters._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_workstation_clusters_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstation_clusters") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstation_clusters") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListWorkstationClustersRequest.pb(workstations.ListWorkstationClustersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = workstations.ListWorkstationClustersResponse.to_json(workstations.ListWorkstationClustersResponse()) + + request = workstations.ListWorkstationClustersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListWorkstationClustersResponse() + + client.list_workstation_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_workstation_clusters_rest_bad_request(transport: str = 'rest', request_type=workstations.ListWorkstationClustersRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_workstation_clusters(request) + + +def test_list_workstation_clusters_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationClustersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListWorkstationClustersResponse.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_workstation_clusters(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/workstationClusters" % client.transport._host, args[1]) + + +def test_list_workstation_clusters_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_clusters( + workstations.ListWorkstationClustersRequest(), + parent='parent_value', + ) + + +def test_list_workstation_clusters_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListWorkstationClustersResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_workstation_clusters(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.WorkstationCluster) + for i in results) + + pages = list(client.list_workstation_clusters(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", [ + workstations.CreateWorkstationClusterRequest, + dict, +]) +def test_create_workstation_cluster_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["workstation_cluster"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + 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_workstation_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_workstation_cluster_rest_required_fields(request_type=workstations.CreateWorkstationClusterRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["workstation_cluster_id"] = "" + 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 "workstationClusterId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "workstationClusterId" in jsonified_request + assert jsonified_request["workstationClusterId"] == request_init["workstation_cluster_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["workstationClusterId"] = 'workstation_cluster_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_cluster._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", "workstation_cluster_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "workstationClusterId" in jsonified_request + assert jsonified_request["workstationClusterId"] == 'workstation_cluster_id_value' + + client = WorkstationsClient( + 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_workstation_cluster(request) + + expected_params = [ + ( + "workstationClusterId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_workstation_cluster_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_workstation_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("validateOnly", "workstationClusterId", )) & set(("parent", "workstationClusterId", "workstationCluster", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_workstation_cluster_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation_cluster") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.CreateWorkstationClusterRequest.pb(workstations.CreateWorkstationClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.CreateWorkstationClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_workstation_cluster_rest_bad_request(transport: str = 'rest', request_type=workstations.CreateWorkstationClusterRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["workstation_cluster"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_workstation_cluster(request) + + +def test_create_workstation_cluster_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_workstation_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/workstationClusters" % client.transport._host, args[1]) + + +def test_create_workstation_cluster_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_cluster( + workstations.CreateWorkstationClusterRequest(), + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_value', + ) + + +def test_create_workstation_cluster_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationClusterRequest, + dict, +]) +def test_update_workstation_cluster_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} + request_init["workstation_cluster"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + 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_workstation_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_workstation_cluster_rest_required_fields(request_type=workstations.UpdateWorkstationClusterRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_cluster._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_workstation_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WorkstationsClient( + 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_workstation_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_workstation_cluster_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_workstation_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstationCluster", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_workstation_cluster_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation_cluster") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.UpdateWorkstationClusterRequest.pb(workstations.UpdateWorkstationClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.UpdateWorkstationClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_workstation_cluster_rest_bad_request(transport: str = 'rest', request_type=workstations.UpdateWorkstationClusterRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} + request_init["workstation_cluster"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_workstation_cluster(request) + + +def test_update_workstation_cluster_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + 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 = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + workstation_cluster=workstations.WorkstationCluster(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_workstation_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{workstation_cluster.name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) + + +def test_update_workstation_cluster_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_cluster( + workstations.UpdateWorkstationClusterRequest(), + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_workstation_cluster_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationClusterRequest, + dict, +]) +def test_delete_workstation_cluster_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_workstation_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_workstation_cluster_rest_required_fields(request_type=workstations.DeleteWorkstationClusterRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_cluster._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_workstation_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag", "force", "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 = WorkstationsClient( + 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_workstation_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_workstation_cluster_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_workstation_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "force", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_workstation_cluster_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation_cluster") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.DeleteWorkstationClusterRequest.pb(workstations.DeleteWorkstationClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.DeleteWorkstationClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_workstation_cluster_rest_bad_request(transport: str = 'rest', request_type=workstations.DeleteWorkstationClusterRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_workstation_cluster(request) + + +def test_delete_workstation_cluster_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_workstation_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) + + +def test_delete_workstation_cluster_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_cluster( + workstations.DeleteWorkstationClusterRequest(), + name='name_value', + ) + + +def test_delete_workstation_cluster_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationConfigRequest, + dict, +]) +def test_get_workstation_config_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationConfig( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + degraded=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.WorkstationConfig.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_workstation_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.degraded is True + + +def test_get_workstation_config_rest_required_fields(request_type=workstations.GetWorkstationConfigRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_workstation_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # 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 = workstations.WorkstationConfig.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_workstation_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_workstation_config_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_workstation_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_workstation_config_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation_config") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.GetWorkstationConfigRequest.pb(workstations.GetWorkstationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = workstations.WorkstationConfig.to_json(workstations.WorkstationConfig()) + + request = workstations.GetWorkstationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.WorkstationConfig() + + client.get_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_workstation_config_rest_bad_request(transport: str = 'rest', request_type=workstations.GetWorkstationConfigRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_workstation_config(request) + + +def test_get_workstation_config_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.WorkstationConfig.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_workstation_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) + + +def test_get_workstation_config_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_config( + workstations.GetWorkstationConfigRequest(), + name='name_value', + ) + + +def test_get_workstation_config_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationConfigsRequest, + dict, +]) +def test_list_workstation_configs_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListWorkstationConfigsResponse.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_workstation_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workstation_configs_rest_required_fields(request_type=workstations.ListWorkstationConfigsRequest): + transport_class = transports.WorkstationsRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstation_configs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstation_configs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # 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 = workstations.ListWorkstationConfigsResponse.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_workstation_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_workstation_configs_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_workstation_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_workstation_configs_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstation_configs") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstation_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListWorkstationConfigsRequest.pb(workstations.ListWorkstationConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = workstations.ListWorkstationConfigsResponse.to_json(workstations.ListWorkstationConfigsResponse()) + + request = workstations.ListWorkstationConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListWorkstationConfigsResponse() + + client.list_workstation_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_workstation_configs_rest_bad_request(transport: str = 'rest', request_type=workstations.ListWorkstationConfigsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_workstation_configs(request) + + +def test_list_workstation_configs_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListWorkstationConfigsResponse.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_workstation_configs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs" % client.transport._host, args[1]) + + +def test_list_workstation_configs_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_configs( + workstations.ListWorkstationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_workstation_configs_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListWorkstationConfigsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + pager = client.list_workstation_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.WorkstationConfig) + for i in results) + + pages = list(client.list_workstation_configs(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", [ + workstations.ListUsableWorkstationConfigsRequest, + dict, +]) +def test_list_usable_workstation_configs_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListUsableWorkstationConfigsResponse.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_usable_workstation_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_usable_workstation_configs_rest_required_fields(request_type=workstations.ListUsableWorkstationConfigsRequest): + transport_class = transports.WorkstationsRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_usable_workstation_configs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_usable_workstation_configs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # 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 = workstations.ListUsableWorkstationConfigsResponse.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_usable_workstation_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_usable_workstation_configs_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_usable_workstation_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_usable_workstation_configs_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_usable_workstation_configs") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_usable_workstation_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListUsableWorkstationConfigsRequest.pb(workstations.ListUsableWorkstationConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = workstations.ListUsableWorkstationConfigsResponse.to_json(workstations.ListUsableWorkstationConfigsResponse()) + + request = workstations.ListUsableWorkstationConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListUsableWorkstationConfigsResponse() + + client.list_usable_workstation_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_usable_workstation_configs_rest_bad_request(transport: str = 'rest', request_type=workstations.ListUsableWorkstationConfigsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_usable_workstation_configs(request) + + +def test_list_usable_workstation_configs_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListUsableWorkstationConfigsResponse.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_usable_workstation_configs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs:listUsable" % client.transport._host, args[1]) + + +def test_list_usable_workstation_configs_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_usable_workstation_configs( + workstations.ListUsableWorkstationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_usable_workstation_configs_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListUsableWorkstationConfigsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + pager = client.list_usable_workstation_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.WorkstationConfig) + for i in results) + + pages = list(client.list_usable_workstation_configs(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", [ + workstations.CreateWorkstationConfigRequest, + dict, +]) +def test_create_workstation_config_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request_init["workstation_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'enable_nested_virtualization': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792}}, 'persistent_directories': [{'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}, 'mount_path': 'mount_path_value'}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + 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_workstation_config(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_workstation_config_rest_required_fields(request_type=workstations.CreateWorkstationConfigRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["workstation_config_id"] = "" + 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 "workstationConfigId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "workstationConfigId" in jsonified_request + assert jsonified_request["workstationConfigId"] == request_init["workstation_config_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["workstationConfigId"] = 'workstation_config_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_config._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", "workstation_config_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "workstationConfigId" in jsonified_request + assert jsonified_request["workstationConfigId"] == 'workstation_config_id_value' + + client = WorkstationsClient( + 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_workstation_config(request) + + expected_params = [ + ( + "workstationConfigId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_workstation_config_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_workstation_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("validateOnly", "workstationConfigId", )) & set(("parent", "workstationConfigId", "workstationConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_workstation_config_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation_config") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.CreateWorkstationConfigRequest.pb(workstations.CreateWorkstationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.CreateWorkstationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_workstation_config_rest_bad_request(transport: str = 'rest', request_type=workstations.CreateWorkstationConfigRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request_init["workstation_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'enable_nested_virtualization': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792}}, 'persistent_directories': [{'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}, 'mount_path': 'mount_path_value'}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_workstation_config(request) + + +def test_create_workstation_config_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_workstation_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs" % client.transport._host, args[1]) + + +def test_create_workstation_config_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_config( + workstations.CreateWorkstationConfigRequest(), + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_value', + ) + + +def test_create_workstation_config_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationConfigRequest, + dict, +]) +def test_update_workstation_config_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} + request_init["workstation_config"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'enable_nested_virtualization': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792}}, 'persistent_directories': [{'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}, 'mount_path': 'mount_path_value'}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + 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_workstation_config(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_workstation_config_rest_required_fields(request_type=workstations.UpdateWorkstationConfigRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_workstation_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WorkstationsClient( + 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_workstation_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_workstation_config_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_workstation_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstationConfig", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_workstation_config_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation_config") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.UpdateWorkstationConfigRequest.pb(workstations.UpdateWorkstationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.UpdateWorkstationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_workstation_config_rest_bad_request(transport: str = 'rest', request_type=workstations.UpdateWorkstationConfigRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} + request_init["workstation_config"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'enable_nested_virtualization': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792}}, 'persistent_directories': [{'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}, 'mount_path': 'mount_path_value'}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_workstation_config(request) + + +def test_update_workstation_config_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + 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 = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + workstation_config=workstations.WorkstationConfig(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_workstation_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{workstation_config.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) + + +def test_update_workstation_config_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_config( + workstations.UpdateWorkstationConfigRequest(), + workstation_config=workstations.WorkstationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_workstation_config_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationConfigRequest, + dict, +]) +def test_delete_workstation_config_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = 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_workstation_config(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_workstation_config_rest_required_fields(request_type=workstations.DeleteWorkstationConfigRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_workstation_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag", "force", "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 = WorkstationsClient( + 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_workstation_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_workstation_config_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_workstation_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "force", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_workstation_config_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation_config") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.DeleteWorkstationConfigRequest.pb(workstations.DeleteWorkstationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.DeleteWorkstationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_workstation_config_rest_bad_request(transport: str = 'rest', request_type=workstations.DeleteWorkstationConfigRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_workstation_config(request) + + +def test_delete_workstation_config_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_workstation_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_workstation_config_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_config( + workstations.DeleteWorkstationConfigRequest(), + name='name_value', + ) + + +def test_delete_workstation_config_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationRequest, + dict, +]) +def test_get_workstation_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.Workstation( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + state=workstations.Workstation.State.STATE_STARTING, + host='host_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.Workstation.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_workstation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.Workstation) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.state == workstations.Workstation.State.STATE_STARTING + assert response.host == 'host_value' + + +def test_get_workstation_rest_required_fields(request_type=workstations.GetWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation._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_workstation._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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.Workstation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # 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 = workstations.Workstation.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_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.GetWorkstationRequest.pb(workstations.GetWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = workstations.Workstation.to_json(workstations.Workstation()) + + request = workstations.GetWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.Workstation() + + client.get_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.GetWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_workstation(request) + + +def test_get_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.Workstation() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.Workstation.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_workstation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) + + +def test_get_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation( + workstations.GetWorkstationRequest(), + name='name_value', + ) + + +def test_get_workstation_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationsRequest, + dict, +]) +def test_list_workstations_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListWorkstationsResponse.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_workstations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workstations_rest_required_fields(request_type=workstations.ListWorkstationsRequest): + transport_class = transports.WorkstationsRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstations._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # 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 = workstations.ListWorkstationsResponse.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_workstations(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_workstations_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_workstations._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_workstations_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstations") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListWorkstationsRequest.pb(workstations.ListWorkstationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = workstations.ListWorkstationsResponse.to_json(workstations.ListWorkstationsResponse()) + + request = workstations.ListWorkstationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListWorkstationsResponse() + + client.list_workstations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_workstations_rest_bad_request(transport: str = 'rest', request_type=workstations.ListWorkstationsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_workstations(request) + + +def test_list_workstations_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListWorkstationsResponse.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_workstations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations" % client.transport._host, args[1]) + + +def test_list_workstations_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstations( + workstations.ListWorkstationsRequest(), + parent='parent_value', + ) + + +def test_list_workstations_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListWorkstationsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + pager = client.list_workstations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.Workstation) + for i in results) + + pages = list(client.list_workstations(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", [ + workstations.ListUsableWorkstationsRequest, + dict, +]) +def test_list_usable_workstations_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListUsableWorkstationsResponse.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_usable_workstations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_usable_workstations_rest_required_fields(request_type=workstations.ListUsableWorkstationsRequest): + transport_class = transports.WorkstationsRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_usable_workstations._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_usable_workstations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # 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 = workstations.ListUsableWorkstationsResponse.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_usable_workstations(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_usable_workstations_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_usable_workstations._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_usable_workstations_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_usable_workstations") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_usable_workstations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListUsableWorkstationsRequest.pb(workstations.ListUsableWorkstationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = workstations.ListUsableWorkstationsResponse.to_json(workstations.ListUsableWorkstationsResponse()) + + request = workstations.ListUsableWorkstationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListUsableWorkstationsResponse() + + client.list_usable_workstations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_usable_workstations_rest_bad_request(transport: str = 'rest', request_type=workstations.ListUsableWorkstationsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_usable_workstations(request) + + +def test_list_usable_workstations_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListUsableWorkstationsResponse.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_usable_workstations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations:listUsable" % client.transport._host, args[1]) + + +def test_list_usable_workstations_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_usable_workstations( + workstations.ListUsableWorkstationsRequest(), + parent='parent_value', + ) + + +def test_list_usable_workstations_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListUsableWorkstationsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + pager = client.list_usable_workstations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.Workstation) + for i in results) + + pages = list(client.list_usable_workstations(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", [ + workstations.CreateWorkstationRequest, + dict, +]) +def test_create_workstation_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request_init["workstation"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_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_workstation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_workstation_rest_required_fields(request_type=workstations.CreateWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["workstation_id"] = "" + 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 "workstationId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "workstationId" in jsonified_request + assert jsonified_request["workstationId"] == request_init["workstation_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["workstationId"] = 'workstation_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation._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", "workstation_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "workstationId" in jsonified_request + assert jsonified_request["workstationId"] == 'workstation_id_value' + + client = WorkstationsClient( + 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_workstation(request) + + expected_params = [ + ( + "workstationId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("validateOnly", "workstationId", )) & set(("parent", "workstationId", "workstation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.CreateWorkstationRequest.pb(workstations.CreateWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.CreateWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.CreateWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request_init["workstation"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_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_workstation(request) + + +def test_create_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_workstation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations" % client.transport._host, args[1]) + + +def test_create_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation( + workstations.CreateWorkstationRequest(), + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_value', + ) + + +def test_create_workstation_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationRequest, + dict, +]) +def test_update_workstation_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} + request_init["workstation"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_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_workstation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_workstation_rest_required_fields(request_type=workstations.UpdateWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation._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_workstation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WorkstationsClient( + 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_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstation", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.UpdateWorkstationRequest.pb(workstations.UpdateWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.UpdateWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.UpdateWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} + request_init["workstation"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_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_workstation(request) + + +def test_update_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + 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 = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} + + # get truthy value for each flattened field + mock_args = dict( + workstation=workstations.Workstation(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_workstation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{workstation.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) + + +def test_update_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation( + workstations.UpdateWorkstationRequest(), + workstation=workstations.Workstation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_workstation_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationRequest, + dict, +]) +def test_delete_workstation_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = 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_workstation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_workstation_rest_required_fields(request_type=workstations.DeleteWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation._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_workstation._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 = WorkstationsClient( + 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_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.DeleteWorkstationRequest.pb(workstations.DeleteWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.DeleteWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.DeleteWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_workstation(request) + + +def test_delete_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_workstation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) + + +def test_delete_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation( + workstations.DeleteWorkstationRequest(), + name='name_value', + ) + + +def test_delete_workstation_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.StartWorkstationRequest, + dict, +]) +def test_start_workstation_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = 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.start_workstation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_start_workstation_rest_required_fields(request_type=workstations.StartWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + 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()).start_workstation._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()).start_workstation._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 = WorkstationsClient( + 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.start_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_start_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.start_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_start_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_start_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_start_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.StartWorkstationRequest.pb(workstations.StartWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.StartWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.start_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_start_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.StartWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.start_workstation(request) + + +def test_start_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.start_workstation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:start" % client.transport._host, args[1]) + + +def test_start_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.start_workstation( + workstations.StartWorkstationRequest(), + name='name_value', + ) + + +def test_start_workstation_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.StopWorkstationRequest, + dict, +]) +def test_stop_workstation_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = 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.stop_workstation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_stop_workstation_rest_required_fields(request_type=workstations.StopWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + 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()).stop_workstation._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()).stop_workstation._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 = WorkstationsClient( + 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.stop_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_stop_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.stop_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_stop_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_stop_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_stop_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.StopWorkstationRequest.pb(workstations.StopWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.StopWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.stop_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_stop_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.StopWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.stop_workstation(request) + + +def test_stop_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.stop_workstation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:stop" % client.transport._host, args[1]) + + +def test_stop_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.stop_workstation( + workstations.StopWorkstationRequest(), + name='name_value', + ) + + +def test_stop_workstation_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GenerateAccessTokenRequest, + dict, +]) +def test_generate_access_token_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.GenerateAccessTokenResponse( + access_token='access_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.GenerateAccessTokenResponse.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.generate_access_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.GenerateAccessTokenResponse) + assert response.access_token == 'access_token_value' + + +def test_generate_access_token_rest_required_fields(request_type=workstations.GenerateAccessTokenRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["workstation"] = "" + 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()).generate_access_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["workstation"] = 'workstation_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_access_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "workstation" in jsonified_request + assert jsonified_request["workstation"] == 'workstation_value' + + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.GenerateAccessTokenResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # 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 + + pb_return_value = workstations.GenerateAccessTokenResponse.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.generate_access_token(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_access_token_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_access_token._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("workstation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_access_token_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_generate_access_token") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_generate_access_token") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.GenerateAccessTokenRequest.pb(workstations.GenerateAccessTokenRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = workstations.GenerateAccessTokenResponse.to_json(workstations.GenerateAccessTokenResponse()) + + request = workstations.GenerateAccessTokenRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.GenerateAccessTokenResponse() + + client.generate_access_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_access_token_rest_bad_request(transport: str = 'rest', request_type=workstations.GenerateAccessTokenRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.generate_access_token(request) + + +def test_generate_access_token_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.GenerateAccessTokenResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + workstation='workstation_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 = workstations.GenerateAccessTokenResponse.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.generate_access_token(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{workstation=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:generateAccessToken" % client.transport._host, args[1]) + + +def test_generate_access_token_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_access_token( + workstations.GenerateAccessTokenRequest(), + workstation='workstation_value', + ) + + +def test_generate_access_token_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WorkstationsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WorkstationsClient( + 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 = WorkstationsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WorkstationsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WorkstationsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WorkstationsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.WorkstationsGrpcTransport, + transports.WorkstationsGrpcAsyncIOTransport, + transports.WorkstationsRestTransport, +]) +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 = WorkstationsClient.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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WorkstationsGrpcTransport, + ) + +def test_workstations_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WorkstationsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_workstations_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.workstations_v1.services.workstations.transports.WorkstationsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.WorkstationsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_workstation_cluster', + 'list_workstation_clusters', + 'create_workstation_cluster', + 'update_workstation_cluster', + 'delete_workstation_cluster', + 'get_workstation_config', + 'list_workstation_configs', + 'list_usable_workstation_configs', + 'create_workstation_config', + 'update_workstation_config', + 'delete_workstation_config', + 'get_workstation', + 'list_workstations', + 'list_usable_workstations', + 'create_workstation', + 'update_workstation', + 'delete_workstation', + 'start_workstation', + 'stop_workstation', + 'generate_access_token', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_workstations_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.workstations_v1.services.workstations.transports.WorkstationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WorkstationsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_workstations_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.workstations_v1.services.workstations.transports.WorkstationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WorkstationsTransport() + adc.assert_called_once() + + +def test_workstations_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) + WorkstationsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WorkstationsGrpcTransport, + transports.WorkstationsGrpcAsyncIOTransport, + ], +) +def test_workstations_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WorkstationsGrpcTransport, + transports.WorkstationsGrpcAsyncIOTransport, + transports.WorkstationsRestTransport, + ], +) +def test_workstations_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.WorkstationsGrpcTransport, grpc_helpers), + (transports.WorkstationsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_workstations_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( + "workstations.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="workstations.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) +def test_workstations_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_workstations_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.WorkstationsRestTransport ( + 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_workstations_rest_lro_client(): + client = WorkstationsClient( + 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_workstations_host_no_port(transport_name): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='workstations.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'workstations.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://workstations.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_workstations_host_with_port(transport_name): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='workstations.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'workstations.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://workstations.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_workstations_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = WorkstationsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = WorkstationsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_workstation_cluster._session + session2 = client2.transport.get_workstation_cluster._session + assert session1 != session2 + session1 = client1.transport.list_workstation_clusters._session + session2 = client2.transport.list_workstation_clusters._session + assert session1 != session2 + session1 = client1.transport.create_workstation_cluster._session + session2 = client2.transport.create_workstation_cluster._session + assert session1 != session2 + session1 = client1.transport.update_workstation_cluster._session + session2 = client2.transport.update_workstation_cluster._session + assert session1 != session2 + session1 = client1.transport.delete_workstation_cluster._session + session2 = client2.transport.delete_workstation_cluster._session + assert session1 != session2 + session1 = client1.transport.get_workstation_config._session + session2 = client2.transport.get_workstation_config._session + assert session1 != session2 + session1 = client1.transport.list_workstation_configs._session + session2 = client2.transport.list_workstation_configs._session + assert session1 != session2 + session1 = client1.transport.list_usable_workstation_configs._session + session2 = client2.transport.list_usable_workstation_configs._session + assert session1 != session2 + session1 = client1.transport.create_workstation_config._session + session2 = client2.transport.create_workstation_config._session + assert session1 != session2 + session1 = client1.transport.update_workstation_config._session + session2 = client2.transport.update_workstation_config._session + assert session1 != session2 + session1 = client1.transport.delete_workstation_config._session + session2 = client2.transport.delete_workstation_config._session + assert session1 != session2 + session1 = client1.transport.get_workstation._session + session2 = client2.transport.get_workstation._session + assert session1 != session2 + session1 = client1.transport.list_workstations._session + session2 = client2.transport.list_workstations._session + assert session1 != session2 + session1 = client1.transport.list_usable_workstations._session + session2 = client2.transport.list_usable_workstations._session + assert session1 != session2 + session1 = client1.transport.create_workstation._session + session2 = client2.transport.create_workstation._session + assert session1 != session2 + session1 = client1.transport.update_workstation._session + session2 = client2.transport.update_workstation._session + assert session1 != session2 + session1 = client1.transport.delete_workstation._session + session2 = client2.transport.delete_workstation._session + assert session1 != session2 + session1 = client1.transport.start_workstation._session + session2 = client2.transport.start_workstation._session + assert session1 != session2 + session1 = client1.transport.stop_workstation._session + session2 = client2.transport.stop_workstation._session + assert session1 != session2 + session1 = client1.transport.generate_access_token._session + session2 = client2.transport.generate_access_token._session + assert session1 != session2 +def test_workstations_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WorkstationsGrpcTransport( + 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_workstations_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WorkstationsGrpcAsyncIOTransport( + 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.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) +def test_workstations_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.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) +def test_workstations_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_workstations_grpc_lro_client(): + client = WorkstationsClient( + 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_workstations_grpc_lro_async_client(): + client = WorkstationsAsyncClient( + 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_workstation_path(): + project = "squid" + location = "clam" + workstation_cluster = "whelk" + workstation_config = "octopus" + workstation = "oyster" + expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}/workstations/{workstation}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, workstation=workstation, ) + actual = WorkstationsClient.workstation_path(project, location, workstation_cluster, workstation_config, workstation) + assert expected == actual + + +def test_parse_workstation_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "workstation_cluster": "mussel", + "workstation_config": "winkle", + "workstation": "nautilus", + } + path = WorkstationsClient.workstation_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_workstation_path(path) + assert expected == actual + +def test_workstation_cluster_path(): + project = "scallop" + location = "abalone" + workstation_cluster = "squid" + expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}".format(project=project, location=location, workstation_cluster=workstation_cluster, ) + actual = WorkstationsClient.workstation_cluster_path(project, location, workstation_cluster) + assert expected == actual + + +def test_parse_workstation_cluster_path(): + expected = { + "project": "clam", + "location": "whelk", + "workstation_cluster": "octopus", + } + path = WorkstationsClient.workstation_cluster_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_workstation_cluster_path(path) + assert expected == actual + +def test_workstation_config_path(): + project = "oyster" + location = "nudibranch" + workstation_cluster = "cuttlefish" + workstation_config = "mussel" + expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, ) + actual = WorkstationsClient.workstation_config_path(project, location, workstation_cluster, workstation_config) + assert expected == actual + + +def test_parse_workstation_config_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "workstation_cluster": "scallop", + "workstation_config": "abalone", + } + path = WorkstationsClient.workstation_config_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_workstation_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = WorkstationsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = WorkstationsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = WorkstationsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = WorkstationsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = WorkstationsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = WorkstationsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = WorkstationsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = WorkstationsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = WorkstationsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = WorkstationsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.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.WorkstationsTransport, '_prep_wrapped_messages') as prep: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.WorkstationsTransport, '_prep_wrapped_messages') as prep: + transport_class = WorkstationsClient.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 = WorkstationsAsyncClient( + 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_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc"): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_delete_operation_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc"): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = WorkstationsAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = WorkstationsAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = WorkstationsAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = WorkstationsClient( + 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 = WorkstationsClient( + 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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/.coveragerc b/owl-bot-staging/google-cloud-workstations/v1beta/.coveragerc new file mode 100644 index 000000000000..ee1a17c3e2ca --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/workstations/__init__.py + google/cloud/workstations/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/.flake8 b/owl-bot-staging/google-cloud-workstations/v1beta/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/MANIFEST.in b/owl-bot-staging/google-cloud-workstations/v1beta/MANIFEST.in new file mode 100644 index 000000000000..ebef07fddb1d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/workstations *.py +recursive-include google/cloud/workstations_v1beta *.py diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/README.rst b/owl-bot-staging/google-cloud-workstations/v1beta/README.rst new file mode 100644 index 000000000000..48a711be018f --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Workstations 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 Workstations API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/docs/conf.py b/owl-bot-staging/google-cloud-workstations/v1beta/docs/conf.py new file mode 100644 index 000000000000..06f3a6eac397 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-workstations 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-workstations" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 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-workstations-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-workstations.tex", + u"google-cloud-workstations 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-workstations", + u"Google Cloud Workstations 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-workstations", + u"google-cloud-workstations Documentation", + author, + "google-cloud-workstations", + "GAPIC library for Google Cloud Workstations API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/docs/index.rst b/owl-bot-staging/google-cloud-workstations/v1beta/docs/index.rst new file mode 100644 index 000000000000..4454f94e00e1 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + workstations_v1beta/services + workstations_v1beta/types diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/services.rst b/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/services.rst new file mode 100644 index 000000000000..77aed9f52d7a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Workstations v1beta API +================================================= +.. toctree:: + :maxdepth: 2 + + workstations diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/types.rst b/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/types.rst new file mode 100644 index 000000000000..af7f36fbcb60 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Workstations v1beta API +============================================== + +.. automodule:: google.cloud.workstations_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/workstations.rst b/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/workstations.rst new file mode 100644 index 000000000000..5839880c918a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/workstations.rst @@ -0,0 +1,10 @@ +Workstations +------------------------------ + +.. automodule:: google.cloud.workstations_v1beta.services.workstations + :members: + :inherited-members: + +.. automodule:: google.cloud.workstations_v1beta.services.workstations.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/__init__.py new file mode 100644 index 000000000000..7876f1ab4d1a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/__init__.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.workstations import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.workstations_v1beta.services.workstations.client import WorkstationsClient +from google.cloud.workstations_v1beta.services.workstations.async_client import WorkstationsAsyncClient + +from google.cloud.workstations_v1beta.types.workstations import CreateWorkstationClusterRequest +from google.cloud.workstations_v1beta.types.workstations import CreateWorkstationConfigRequest +from google.cloud.workstations_v1beta.types.workstations import CreateWorkstationRequest +from google.cloud.workstations_v1beta.types.workstations import DeleteWorkstationClusterRequest +from google.cloud.workstations_v1beta.types.workstations import DeleteWorkstationConfigRequest +from google.cloud.workstations_v1beta.types.workstations import DeleteWorkstationRequest +from google.cloud.workstations_v1beta.types.workstations import GenerateAccessTokenRequest +from google.cloud.workstations_v1beta.types.workstations import GenerateAccessTokenResponse +from google.cloud.workstations_v1beta.types.workstations import GetWorkstationClusterRequest +from google.cloud.workstations_v1beta.types.workstations import GetWorkstationConfigRequest +from google.cloud.workstations_v1beta.types.workstations import GetWorkstationRequest +from google.cloud.workstations_v1beta.types.workstations import ListUsableWorkstationConfigsRequest +from google.cloud.workstations_v1beta.types.workstations import ListUsableWorkstationConfigsResponse +from google.cloud.workstations_v1beta.types.workstations import ListUsableWorkstationsRequest +from google.cloud.workstations_v1beta.types.workstations import ListUsableWorkstationsResponse +from google.cloud.workstations_v1beta.types.workstations import ListWorkstationClustersRequest +from google.cloud.workstations_v1beta.types.workstations import ListWorkstationClustersResponse +from google.cloud.workstations_v1beta.types.workstations import ListWorkstationConfigsRequest +from google.cloud.workstations_v1beta.types.workstations import ListWorkstationConfigsResponse +from google.cloud.workstations_v1beta.types.workstations import ListWorkstationsRequest +from google.cloud.workstations_v1beta.types.workstations import ListWorkstationsResponse +from google.cloud.workstations_v1beta.types.workstations import OperationMetadata +from google.cloud.workstations_v1beta.types.workstations import StartWorkstationRequest +from google.cloud.workstations_v1beta.types.workstations import StopWorkstationRequest +from google.cloud.workstations_v1beta.types.workstations import UpdateWorkstationClusterRequest +from google.cloud.workstations_v1beta.types.workstations import UpdateWorkstationConfigRequest +from google.cloud.workstations_v1beta.types.workstations import UpdateWorkstationRequest +from google.cloud.workstations_v1beta.types.workstations import Workstation +from google.cloud.workstations_v1beta.types.workstations import WorkstationCluster +from google.cloud.workstations_v1beta.types.workstations import WorkstationConfig + +__all__ = ('WorkstationsClient', + 'WorkstationsAsyncClient', + 'CreateWorkstationClusterRequest', + 'CreateWorkstationConfigRequest', + 'CreateWorkstationRequest', + 'DeleteWorkstationClusterRequest', + 'DeleteWorkstationConfigRequest', + 'DeleteWorkstationRequest', + 'GenerateAccessTokenRequest', + 'GenerateAccessTokenResponse', + 'GetWorkstationClusterRequest', + 'GetWorkstationConfigRequest', + 'GetWorkstationRequest', + 'ListUsableWorkstationConfigsRequest', + 'ListUsableWorkstationConfigsResponse', + 'ListUsableWorkstationsRequest', + 'ListUsableWorkstationsResponse', + 'ListWorkstationClustersRequest', + 'ListWorkstationClustersResponse', + 'ListWorkstationConfigsRequest', + 'ListWorkstationConfigsResponse', + 'ListWorkstationsRequest', + 'ListWorkstationsResponse', + 'OperationMetadata', + 'StartWorkstationRequest', + 'StopWorkstationRequest', + 'UpdateWorkstationClusterRequest', + 'UpdateWorkstationConfigRequest', + 'UpdateWorkstationRequest', + 'Workstation', + 'WorkstationCluster', + 'WorkstationConfig', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/gapic_version.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/gapic_version.py new file mode 100644 index 000000000000..360a0d13ebdd --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/py.typed b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/py.typed new file mode 100644 index 000000000000..04170223dff9 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-workstations package uses inline types. diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/__init__.py new file mode 100644 index 000000000000..ef2969955daf --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/__init__.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.workstations_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.workstations import WorkstationsClient +from .services.workstations import WorkstationsAsyncClient + +from .types.workstations import CreateWorkstationClusterRequest +from .types.workstations import CreateWorkstationConfigRequest +from .types.workstations import CreateWorkstationRequest +from .types.workstations import DeleteWorkstationClusterRequest +from .types.workstations import DeleteWorkstationConfigRequest +from .types.workstations import DeleteWorkstationRequest +from .types.workstations import GenerateAccessTokenRequest +from .types.workstations import GenerateAccessTokenResponse +from .types.workstations import GetWorkstationClusterRequest +from .types.workstations import GetWorkstationConfigRequest +from .types.workstations import GetWorkstationRequest +from .types.workstations import ListUsableWorkstationConfigsRequest +from .types.workstations import ListUsableWorkstationConfigsResponse +from .types.workstations import ListUsableWorkstationsRequest +from .types.workstations import ListUsableWorkstationsResponse +from .types.workstations import ListWorkstationClustersRequest +from .types.workstations import ListWorkstationClustersResponse +from .types.workstations import ListWorkstationConfigsRequest +from .types.workstations import ListWorkstationConfigsResponse +from .types.workstations import ListWorkstationsRequest +from .types.workstations import ListWorkstationsResponse +from .types.workstations import OperationMetadata +from .types.workstations import StartWorkstationRequest +from .types.workstations import StopWorkstationRequest +from .types.workstations import UpdateWorkstationClusterRequest +from .types.workstations import UpdateWorkstationConfigRequest +from .types.workstations import UpdateWorkstationRequest +from .types.workstations import Workstation +from .types.workstations import WorkstationCluster +from .types.workstations import WorkstationConfig + +__all__ = ( + 'WorkstationsAsyncClient', +'CreateWorkstationClusterRequest', +'CreateWorkstationConfigRequest', +'CreateWorkstationRequest', +'DeleteWorkstationClusterRequest', +'DeleteWorkstationConfigRequest', +'DeleteWorkstationRequest', +'GenerateAccessTokenRequest', +'GenerateAccessTokenResponse', +'GetWorkstationClusterRequest', +'GetWorkstationConfigRequest', +'GetWorkstationRequest', +'ListUsableWorkstationConfigsRequest', +'ListUsableWorkstationConfigsResponse', +'ListUsableWorkstationsRequest', +'ListUsableWorkstationsResponse', +'ListWorkstationClustersRequest', +'ListWorkstationClustersResponse', +'ListWorkstationConfigsRequest', +'ListWorkstationConfigsResponse', +'ListWorkstationsRequest', +'ListWorkstationsResponse', +'OperationMetadata', +'StartWorkstationRequest', +'StopWorkstationRequest', +'UpdateWorkstationClusterRequest', +'UpdateWorkstationConfigRequest', +'UpdateWorkstationRequest', +'Workstation', +'WorkstationCluster', +'WorkstationConfig', +'WorkstationsClient', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_metadata.json b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..cf8a80968ec1 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_metadata.json @@ -0,0 +1,328 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.workstations_v1beta", + "protoPackage": "google.cloud.workstations.v1beta", + "schema": "1.0", + "services": { + "Workstations": { + "clients": { + "grpc": { + "libraryClient": "WorkstationsClient", + "rpcs": { + "CreateWorkstation": { + "methods": [ + "create_workstation" + ] + }, + "CreateWorkstationCluster": { + "methods": [ + "create_workstation_cluster" + ] + }, + "CreateWorkstationConfig": { + "methods": [ + "create_workstation_config" + ] + }, + "DeleteWorkstation": { + "methods": [ + "delete_workstation" + ] + }, + "DeleteWorkstationCluster": { + "methods": [ + "delete_workstation_cluster" + ] + }, + "DeleteWorkstationConfig": { + "methods": [ + "delete_workstation_config" + ] + }, + "GenerateAccessToken": { + "methods": [ + "generate_access_token" + ] + }, + "GetWorkstation": { + "methods": [ + "get_workstation" + ] + }, + "GetWorkstationCluster": { + "methods": [ + "get_workstation_cluster" + ] + }, + "GetWorkstationConfig": { + "methods": [ + "get_workstation_config" + ] + }, + "ListUsableWorkstationConfigs": { + "methods": [ + "list_usable_workstation_configs" + ] + }, + "ListUsableWorkstations": { + "methods": [ + "list_usable_workstations" + ] + }, + "ListWorkstationClusters": { + "methods": [ + "list_workstation_clusters" + ] + }, + "ListWorkstationConfigs": { + "methods": [ + "list_workstation_configs" + ] + }, + "ListWorkstations": { + "methods": [ + "list_workstations" + ] + }, + "StartWorkstation": { + "methods": [ + "start_workstation" + ] + }, + "StopWorkstation": { + "methods": [ + "stop_workstation" + ] + }, + "UpdateWorkstation": { + "methods": [ + "update_workstation" + ] + }, + "UpdateWorkstationCluster": { + "methods": [ + "update_workstation_cluster" + ] + }, + "UpdateWorkstationConfig": { + "methods": [ + "update_workstation_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WorkstationsAsyncClient", + "rpcs": { + "CreateWorkstation": { + "methods": [ + "create_workstation" + ] + }, + "CreateWorkstationCluster": { + "methods": [ + "create_workstation_cluster" + ] + }, + "CreateWorkstationConfig": { + "methods": [ + "create_workstation_config" + ] + }, + "DeleteWorkstation": { + "methods": [ + "delete_workstation" + ] + }, + "DeleteWorkstationCluster": { + "methods": [ + "delete_workstation_cluster" + ] + }, + "DeleteWorkstationConfig": { + "methods": [ + "delete_workstation_config" + ] + }, + "GenerateAccessToken": { + "methods": [ + "generate_access_token" + ] + }, + "GetWorkstation": { + "methods": [ + "get_workstation" + ] + }, + "GetWorkstationCluster": { + "methods": [ + "get_workstation_cluster" + ] + }, + "GetWorkstationConfig": { + "methods": [ + "get_workstation_config" + ] + }, + "ListUsableWorkstationConfigs": { + "methods": [ + "list_usable_workstation_configs" + ] + }, + "ListUsableWorkstations": { + "methods": [ + "list_usable_workstations" + ] + }, + "ListWorkstationClusters": { + "methods": [ + "list_workstation_clusters" + ] + }, + "ListWorkstationConfigs": { + "methods": [ + "list_workstation_configs" + ] + }, + "ListWorkstations": { + "methods": [ + "list_workstations" + ] + }, + "StartWorkstation": { + "methods": [ + "start_workstation" + ] + }, + "StopWorkstation": { + "methods": [ + "stop_workstation" + ] + }, + "UpdateWorkstation": { + "methods": [ + "update_workstation" + ] + }, + "UpdateWorkstationCluster": { + "methods": [ + "update_workstation_cluster" + ] + }, + "UpdateWorkstationConfig": { + "methods": [ + "update_workstation_config" + ] + } + } + }, + "rest": { + "libraryClient": "WorkstationsClient", + "rpcs": { + "CreateWorkstation": { + "methods": [ + "create_workstation" + ] + }, + "CreateWorkstationCluster": { + "methods": [ + "create_workstation_cluster" + ] + }, + "CreateWorkstationConfig": { + "methods": [ + "create_workstation_config" + ] + }, + "DeleteWorkstation": { + "methods": [ + "delete_workstation" + ] + }, + "DeleteWorkstationCluster": { + "methods": [ + "delete_workstation_cluster" + ] + }, + "DeleteWorkstationConfig": { + "methods": [ + "delete_workstation_config" + ] + }, + "GenerateAccessToken": { + "methods": [ + "generate_access_token" + ] + }, + "GetWorkstation": { + "methods": [ + "get_workstation" + ] + }, + "GetWorkstationCluster": { + "methods": [ + "get_workstation_cluster" + ] + }, + "GetWorkstationConfig": { + "methods": [ + "get_workstation_config" + ] + }, + "ListUsableWorkstationConfigs": { + "methods": [ + "list_usable_workstation_configs" + ] + }, + "ListUsableWorkstations": { + "methods": [ + "list_usable_workstations" + ] + }, + "ListWorkstationClusters": { + "methods": [ + "list_workstation_clusters" + ] + }, + "ListWorkstationConfigs": { + "methods": [ + "list_workstation_configs" + ] + }, + "ListWorkstations": { + "methods": [ + "list_workstations" + ] + }, + "StartWorkstation": { + "methods": [ + "start_workstation" + ] + }, + "StopWorkstation": { + "methods": [ + "stop_workstation" + ] + }, + "UpdateWorkstation": { + "methods": [ + "update_workstation" + ] + }, + "UpdateWorkstationCluster": { + "methods": [ + "update_workstation_cluster" + ] + }, + "UpdateWorkstationConfig": { + "methods": [ + "update_workstation_config" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_version.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_version.py new file mode 100644 index 000000000000..360a0d13ebdd --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/py.typed b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/py.typed new file mode 100644 index 000000000000..04170223dff9 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-workstations package uses inline types. diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/__init__.py new file mode 100644 index 000000000000..0d8e475505ba --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 WorkstationsClient +from .async_client import WorkstationsAsyncClient + +__all__ = ( + 'WorkstationsClient', + 'WorkstationsAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/async_client.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/async_client.py new file mode 100644 index 000000000000..f502c173f6a2 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/async_client.py @@ -0,0 +1,3093 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.workstations_v1beta 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.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1beta.services.workstations import pagers +from google.cloud.workstations_v1beta.types import workstations +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 +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import WorkstationsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import WorkstationsGrpcAsyncIOTransport +from .client import WorkstationsClient + + +class WorkstationsAsyncClient: + """Service for interacting with Cloud Workstations.""" + + _client: WorkstationsClient + + DEFAULT_ENDPOINT = WorkstationsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = WorkstationsClient.DEFAULT_MTLS_ENDPOINT + + workstation_path = staticmethod(WorkstationsClient.workstation_path) + parse_workstation_path = staticmethod(WorkstationsClient.parse_workstation_path) + workstation_cluster_path = staticmethod(WorkstationsClient.workstation_cluster_path) + parse_workstation_cluster_path = staticmethod(WorkstationsClient.parse_workstation_cluster_path) + workstation_config_path = staticmethod(WorkstationsClient.workstation_config_path) + parse_workstation_config_path = staticmethod(WorkstationsClient.parse_workstation_config_path) + common_billing_account_path = staticmethod(WorkstationsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(WorkstationsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(WorkstationsClient.common_folder_path) + parse_common_folder_path = staticmethod(WorkstationsClient.parse_common_folder_path) + common_organization_path = staticmethod(WorkstationsClient.common_organization_path) + parse_common_organization_path = staticmethod(WorkstationsClient.parse_common_organization_path) + common_project_path = staticmethod(WorkstationsClient.common_project_path) + parse_common_project_path = staticmethod(WorkstationsClient.parse_common_project_path) + common_location_path = staticmethod(WorkstationsClient.common_location_path) + parse_common_location_path = staticmethod(WorkstationsClient.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: + WorkstationsAsyncClient: The constructed client. + """ + return WorkstationsClient.from_service_account_info.__func__(WorkstationsAsyncClient, 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: + WorkstationsAsyncClient: The constructed client. + """ + return WorkstationsClient.from_service_account_file.__func__(WorkstationsAsyncClient, 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 WorkstationsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> WorkstationsTransport: + """Returns the transport used by the client instance. + + Returns: + WorkstationsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(WorkstationsClient).get_transport_class, type(WorkstationsClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, WorkstationsTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the workstations 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, ~.WorkstationsTransport]): 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 = WorkstationsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_workstation_cluster(self, + request: Optional[Union[workstations.GetWorkstationClusterRequest, 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]] = (), + ) -> workstations.WorkstationCluster: + r"""Returns the requested workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_get_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.GetWorkstationClusterRequest, dict]]): + The request object. Request message for + GetWorkstationCluster. + name (:class:`str`): + Required. Name of the requested + resource. + + 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.workstations_v1beta.types.WorkstationCluster: + A grouping of workstation + configurations and the associated + workstations in that region. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = workstations.GetWorkstationClusterRequest(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_workstation_cluster, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_workstation_clusters(self, + request: Optional[Union[workstations.ListWorkstationClustersRequest, 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.ListWorkstationClustersAsyncPager: + r"""Returns all workstation clusters in the specified + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_list_workstation_clusters(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest, dict]]): + The request object. Request message for + ListWorkstationClusters. + parent (:class:`str`): + Required. Parent resource name. + 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.workstations_v1beta.services.workstations.pagers.ListWorkstationClustersAsyncPager: + Response message for + ListWorkstationClusters. + 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 = workstations.ListWorkstationClustersRequest(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_workstation_clusters, + default_retry=retries.Retry( +initial=1.0,maximum=10.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(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListWorkstationClustersAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_workstation_cluster(self, + request: Optional[Union[workstations.CreateWorkstationClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation_cluster: Optional[workstations.WorkstationCluster] = None, + workstation_cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_create_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationClusterRequest( + parent="parent_value", + workstation_cluster_id="workstation_cluster_id_value", + ) + + # Make the request + operation = client.create_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.CreateWorkstationClusterRequest, dict]]): + The request object. Message for creating a + CreateWorkstationCluster. + parent (:class:`str`): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_cluster (:class:`google.cloud.workstations_v1beta.types.WorkstationCluster`): + Required. Workstation cluster to + create. + + This corresponds to the ``workstation_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_cluster_id (:class:`str`): + Required. ID to use for the + workstation cluster. + + This corresponds to the ``workstation_cluster_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.workstations_v1beta.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations + in that region. + + """ + # Create or coerce a protobuf request object. + # Quick 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, workstation_cluster, workstation_cluster_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = workstations.CreateWorkstationClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation_cluster is not None: + request.workstation_cluster = workstation_cluster + if workstation_cluster_id is not None: + request.workstation_cluster_id = workstation_cluster_id + + # 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_workstation_cluster, + 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(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_workstation_cluster(self, + request: Optional[Union[workstations.UpdateWorkstationClusterRequest, dict]] = None, + *, + workstation_cluster: Optional[workstations.WorkstationCluster] = 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 an existing workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_update_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationClusterRequest( + ) + + # Make the request + operation = client.update_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.UpdateWorkstationClusterRequest, dict]]): + The request object. Request message for + UpdateWorkstationCluster. + workstation_cluster (:class:`google.cloud.workstations_v1beta.types.WorkstationCluster`): + Required. Workstation cluster to + update. + + This corresponds to the ``workstation_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Mask that specifies which + fields in the workstation cluster should + 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.workstations_v1beta.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations + in that region. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation_cluster, 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 = workstations.UpdateWorkstationClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation_cluster is not None: + request.workstation_cluster = workstation_cluster + 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_workstation_cluster, + 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(( + ("workstation_cluster.name", request.workstation_cluster.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, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_workstation_cluster(self, + request: Optional[Union[workstations.DeleteWorkstationClusterRequest, 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 the specified workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_delete_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.DeleteWorkstationClusterRequest, dict]]): + The request object. Message for deleting a workstation + cluster. + name (:class:`str`): + Required. Name of the workstation + cluster to delete. + + 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.workstations_v1beta.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations + in that region. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = workstations.DeleteWorkstationClusterRequest(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_workstation_cluster, + 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, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_workstation_config(self, + request: Optional[Union[workstations.GetWorkstationConfigRequest, 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]] = (), + ) -> workstations.WorkstationConfig: + r"""Returns the requested workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_get_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.GetWorkstationConfigRequest, dict]]): + The request object. Request message for + GetWorkstationConfig. + name (:class:`str`): + Required. Name of the requested + resource. + + 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.workstations_v1beta.types.WorkstationConfig: + A set of configuration options + describing how a workstation will be + run. Workstation configurations are + intended to be shared across multiple + workstations. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = workstations.GetWorkstationConfigRequest(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_workstation_config, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_workstation_configs(self, + request: Optional[Union[workstations.ListWorkstationConfigsRequest, 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.ListWorkstationConfigsAsyncPager: + r"""Returns all workstation configurations in the + specified cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_list_workstation_configs(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest, dict]]): + The request object. Request message for + ListWorkstationConfigs. + parent (:class:`str`): + Required. Parent resource name. + 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.workstations_v1beta.services.workstations.pagers.ListWorkstationConfigsAsyncPager: + Response message for + ListWorkstationConfigs. + 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 = workstations.ListWorkstationConfigsRequest(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_workstation_configs, + default_retry=retries.Retry( +initial=1.0,maximum=10.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(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListWorkstationConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_usable_workstation_configs(self, + request: Optional[Union[workstations.ListUsableWorkstationConfigsRequest, 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.ListUsableWorkstationConfigsAsyncPager: + r"""Returns all workstation configurations in the + specified cluster on which the caller has the + "workstations.workstation.create" permission. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_list_usable_workstation_configs(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListUsableWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstation_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest, dict]]): + The request object. Request message for + ListUsableWorkstationConfigs. + parent (:class:`str`): + Required. Parent resource name. + 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.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationConfigsAsyncPager: + Response message for + ListUsableWorkstationConfigs. + 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 = workstations.ListUsableWorkstationConfigsRequest(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_usable_workstation_configs, + default_retry=retries.Retry( +initial=1.0,maximum=10.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(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListUsableWorkstationConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_workstation_config(self, + request: Optional[Union[workstations.CreateWorkstationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation_config: Optional[workstations.WorkstationConfig] = None, + workstation_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_create_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationConfigRequest( + parent="parent_value", + workstation_config_id="workstation_config_id_value", + ) + + # Make the request + operation = client.create_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.CreateWorkstationConfigRequest, dict]]): + The request object. Message for creating a + CreateWorkstationConfig. + parent (:class:`str`): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_config (:class:`google.cloud.workstations_v1beta.types.WorkstationConfig`): + Required. Config to create. + This corresponds to the ``workstation_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_config_id (:class:`str`): + Required. ID to use for the + workstation configuration. + + This corresponds to the ``workstation_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.workstations_v1beta.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. + Workstation configurations are intended to be shared + across multiple workstations. + + """ + # Create or coerce a protobuf request object. + # Quick 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, workstation_config, workstation_config_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = workstations.CreateWorkstationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation_config is not None: + request.workstation_config = workstation_config + if workstation_config_id is not None: + request.workstation_config_id = workstation_config_id + + # 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_workstation_config, + 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(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_workstation_config(self, + request: Optional[Union[workstations.UpdateWorkstationConfigRequest, dict]] = None, + *, + workstation_config: Optional[workstations.WorkstationConfig] = 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 an existing workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_update_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationConfigRequest( + ) + + # Make the request + operation = client.update_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.UpdateWorkstationConfigRequest, dict]]): + The request object. Request message for + UpdateWorkstationConfig. + workstation_config (:class:`google.cloud.workstations_v1beta.types.WorkstationConfig`): + Required. Config to update. + This corresponds to the ``workstation_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Mask specifying which + fields in the workstation configuration + should 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.workstations_v1beta.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. + Workstation configurations are intended to be shared + across multiple workstations. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = workstations.UpdateWorkstationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation_config is not None: + request.workstation_config = workstation_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_workstation_config, + 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(( + ("workstation_config.name", request.workstation_config.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, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_workstation_config(self, + request: Optional[Union[workstations.DeleteWorkstationConfigRequest, 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 the specified workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_delete_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.DeleteWorkstationConfigRequest, dict]]): + The request object. Message for deleting a workstation + configuration. + name (:class:`str`): + Required. Name of the workstation + configuration to delete. + + 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.workstations_v1beta.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. + Workstation configurations are intended to be shared + across multiple workstations. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = workstations.DeleteWorkstationConfigRequest(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_workstation_config, + 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, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_workstation(self, + request: Optional[Union[workstations.GetWorkstationRequest, 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]] = (), + ) -> workstations.Workstation: + r"""Returns the requested workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_get_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.GetWorkstationRequest, dict]]): + The request object. Request message for GetWorkstation. + name (:class:`str`): + Required. Name of the requested + resource. + + 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.workstations_v1beta.types.Workstation: + A single instance of a developer + workstation with its own persistent + storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = workstations.GetWorkstationRequest(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_workstation, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_workstations(self, + request: Optional[Union[workstations.ListWorkstationsRequest, 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.ListWorkstationsAsyncPager: + r"""Returns all Workstations using the specified + workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_list_workstations(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.ListWorkstationsRequest, dict]]): + The request object. Request message for ListWorkstations. + parent (:class:`str`): + Required. Parent resource name. + 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.workstations_v1beta.services.workstations.pagers.ListWorkstationsAsyncPager: + Response message for + ListWorkstations. + 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 = workstations.ListWorkstationsRequest(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_workstations, + default_retry=retries.Retry( +initial=1.0,maximum=10.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(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListWorkstationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_usable_workstations(self, + request: Optional[Union[workstations.ListUsableWorkstationsRequest, 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.ListUsableWorkstationsAsyncPager: + r"""Returns all workstations using the specified + workstation configuration on which the caller has the + "workstations.workstations.use" permission. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_list_usable_workstations(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListUsableWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest, dict]]): + The request object. Request message for + ListUsableWorkstations. + parent (:class:`str`): + Required. Parent resource name. + 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.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationsAsyncPager: + Response message for + ListUsableWorkstations. + 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 = workstations.ListUsableWorkstationsRequest(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_usable_workstations, + default_retry=retries.Retry( +initial=1.0,maximum=10.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(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListUsableWorkstationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_workstation(self, + request: Optional[Union[workstations.CreateWorkstationRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation: Optional[workstations.Workstation] = None, + workstation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_create_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationRequest( + parent="parent_value", + workstation_id="workstation_id_value", + ) + + # Make the request + operation = client.create_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.CreateWorkstationRequest, dict]]): + The request object. Message for creating a + CreateWorkstation. + parent (:class:`str`): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation (:class:`google.cloud.workstations_v1beta.types.Workstation`): + Required. Workstation to create. + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_id (:class:`str`): + Required. ID to use for the + workstation. + + This corresponds to the ``workstation_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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, workstation, workstation_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = workstations.CreateWorkstationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation is not None: + request.workstation = workstation + if workstation_id is not None: + request.workstation_id = workstation_id + + # 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_workstation, + 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(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_workstation(self, + request: Optional[Union[workstations.UpdateWorkstationRequest, dict]] = None, + *, + workstation: Optional[workstations.Workstation] = 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 an existing workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_update_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationRequest( + ) + + # Make the request + operation = client.update_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.UpdateWorkstationRequest, dict]]): + The request object. Request message for + UpdateWorkstation. + workstation (:class:`google.cloud.workstations_v1beta.types.Workstation`): + Required. Workstation to update. + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Mask specifying which + fields in the workstation configuration + should 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.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation, 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 = workstations.UpdateWorkstationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation is not None: + request.workstation = workstation + 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_workstation, + 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(( + ("workstation.name", request.workstation.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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_workstation(self, + request: Optional[Union[workstations.DeleteWorkstationRequest, 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 the specified workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_delete_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.DeleteWorkstationRequest, dict]]): + The request object. Request message for + DeleteWorkstation. + name (:class:`str`): + Required. Name of the workstation to + delete. + + 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.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = workstations.DeleteWorkstationRequest(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_workstation, + 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def start_workstation(self, + request: Optional[Union[workstations.StartWorkstationRequest, 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"""Starts running a workstation so that users can + connect to 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 workstations_v1beta + + async def sample_start_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.StartWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.start_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.StartWorkstationRequest, dict]]): + The request object. Request message for StartWorkstation. + name (:class:`str`): + Required. Name of the workstation to + start. + + 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.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = workstations.StartWorkstationRequest(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.start_workstation, + 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def stop_workstation(self, + request: Optional[Union[workstations.StopWorkstationRequest, 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"""Stops running a workstation, reducing costs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_stop_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.StopWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.StopWorkstationRequest, dict]]): + The request object. Request message for StopWorkstation. + name (:class:`str`): + Required. Name of the workstation to + stop. + + 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.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = workstations.StopWorkstationRequest(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.stop_workstation, + 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def generate_access_token(self, + request: Optional[Union[workstations.GenerateAccessTokenRequest, dict]] = None, + *, + workstation: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.GenerateAccessTokenResponse: + r"""Returns a short-lived credential that can be used to + send authenticated and authorized traffic to a + workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + async def sample_generate_access_token(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.GenerateAccessTokenRequest( + workstation="workstation_value", + ) + + # Make the request + response = await client.generate_access_token(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.workstations_v1beta.types.GenerateAccessTokenRequest, dict]]): + The request object. Request message for + GenerateAccessToken. + workstation (:class:`str`): + Required. Name of the workstation for + which the access token should be + generated. + + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1beta.types.GenerateAccessTokenResponse: + Response message for + GenerateAccessToken. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation]) + if request is 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 = workstations.GenerateAccessTokenRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation is not None: + request.workstation = workstation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.generate_access_token, + default_retry=retries.Retry( +initial=1.0,maximum=10.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(( + ("workstation", request.workstation), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._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) -> "WorkstationsAsyncClient": + 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__ = ( + "WorkstationsAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/client.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/client.py new file mode 100644 index 000000000000..8406e4c3e182 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/client.py @@ -0,0 +1,3259 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.workstations_v1beta 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.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1beta.services.workstations import pagers +from google.cloud.workstations_v1beta.types import workstations +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 +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import WorkstationsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import WorkstationsGrpcTransport +from .transports.grpc_asyncio import WorkstationsGrpcAsyncIOTransport +from .transports.rest import WorkstationsRestTransport + + +class WorkstationsClientMeta(type): + """Metaclass for the Workstations 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[WorkstationsTransport]] + _transport_registry["grpc"] = WorkstationsGrpcTransport + _transport_registry["grpc_asyncio"] = WorkstationsGrpcAsyncIOTransport + _transport_registry["rest"] = WorkstationsRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[WorkstationsTransport]: + """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 WorkstationsClient(metaclass=WorkstationsClientMeta): + """Service for interacting with Cloud Workstations.""" + + @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 = "workstations.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: + WorkstationsClient: 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: + WorkstationsClient: 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) -> WorkstationsTransport: + """Returns the transport used by the client instance. + + Returns: + WorkstationsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def workstation_path(project: str,location: str,workstation_cluster: str,workstation_config: str,workstation: str,) -> str: + """Returns a fully-qualified workstation string.""" + return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}/workstations/{workstation}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, workstation=workstation, ) + + @staticmethod + def parse_workstation_path(path: str) -> Dict[str,str]: + """Parses a workstation path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)/workstationConfigs/(?P.+?)/workstations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def workstation_cluster_path(project: str,location: str,workstation_cluster: str,) -> str: + """Returns a fully-qualified workstation_cluster string.""" + return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}".format(project=project, location=location, workstation_cluster=workstation_cluster, ) + + @staticmethod + def parse_workstation_cluster_path(path: str) -> Dict[str,str]: + """Parses a workstation_cluster path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def workstation_config_path(project: str,location: str,workstation_cluster: str,workstation_config: str,) -> str: + """Returns a fully-qualified workstation_config string.""" + return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, ) + + @staticmethod + def parse_workstation_config_path(path: str) -> Dict[str,str]: + """Parses a workstation_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)/workstationConfigs/(?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, WorkstationsTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the workstations 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, WorkstationsTransport]): 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, WorkstationsTransport): + # transport is a WorkstationsTransport 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_workstation_cluster(self, + request: Optional[Union[workstations.GetWorkstationClusterRequest, 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]] = (), + ) -> workstations.WorkstationCluster: + r"""Returns the requested workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_get_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation_cluster(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.GetWorkstationClusterRequest, dict]): + The request object. Request message for + GetWorkstationCluster. + name (str): + Required. Name of the requested + resource. + + 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.workstations_v1beta.types.WorkstationCluster: + A grouping of workstation + configurations and the associated + workstations in that region. + + """ + # Create or coerce a protobuf request object. + # Quick 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 workstations.GetWorkstationClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.GetWorkstationClusterRequest): + request = workstations.GetWorkstationClusterRequest(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_workstation_cluster] + + # Certain 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_workstation_clusters(self, + request: Optional[Union[workstations.ListWorkstationClustersRequest, 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.ListWorkstationClustersPager: + r"""Returns all workstation clusters in the specified + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_list_workstation_clusters(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest, dict]): + The request object. Request message for + ListWorkstationClusters. + parent (str): + Required. Parent resource name. + 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.workstations_v1beta.services.workstations.pagers.ListWorkstationClustersPager: + Response message for + ListWorkstationClusters. + 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 workstations.ListWorkstationClustersRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.ListWorkstationClustersRequest): + request = workstations.ListWorkstationClustersRequest(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_workstation_clusters] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListWorkstationClustersPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_workstation_cluster(self, + request: Optional[Union[workstations.CreateWorkstationClusterRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation_cluster: Optional[workstations.WorkstationCluster] = None, + workstation_cluster_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_create_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationClusterRequest( + parent="parent_value", + workstation_cluster_id="workstation_cluster_id_value", + ) + + # Make the request + operation = client.create_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.CreateWorkstationClusterRequest, dict]): + The request object. Message for creating a + CreateWorkstationCluster. + parent (str): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_cluster (google.cloud.workstations_v1beta.types.WorkstationCluster): + Required. Workstation cluster to + create. + + This corresponds to the ``workstation_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_cluster_id (str): + Required. ID to use for the + workstation cluster. + + This corresponds to the ``workstation_cluster_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.workstations_v1beta.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations + in that region. + + """ + # Create or coerce a protobuf request object. + # Quick 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, workstation_cluster, workstation_cluster_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a workstations.CreateWorkstationClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.CreateWorkstationClusterRequest): + request = workstations.CreateWorkstationClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation_cluster is not None: + request.workstation_cluster = workstation_cluster + if workstation_cluster_id is not None: + request.workstation_cluster_id = workstation_cluster_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_workstation_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_workstation_cluster(self, + request: Optional[Union[workstations.UpdateWorkstationClusterRequest, dict]] = None, + *, + workstation_cluster: Optional[workstations.WorkstationCluster] = 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 an existing workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_update_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationClusterRequest( + ) + + # Make the request + operation = client.update_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.UpdateWorkstationClusterRequest, dict]): + The request object. Request message for + UpdateWorkstationCluster. + workstation_cluster (google.cloud.workstations_v1beta.types.WorkstationCluster): + Required. Workstation cluster to + update. + + This corresponds to the ``workstation_cluster`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask that specifies which + fields in the workstation cluster should + 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.workstations_v1beta.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations + in that region. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation_cluster, 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 workstations.UpdateWorkstationClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.UpdateWorkstationClusterRequest): + request = workstations.UpdateWorkstationClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation_cluster is not None: + request.workstation_cluster = workstation_cluster + 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_workstation_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation_cluster.name", request.workstation_cluster.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, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_workstation_cluster(self, + request: Optional[Union[workstations.DeleteWorkstationClusterRequest, 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 the specified workstation cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_delete_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.DeleteWorkstationClusterRequest, dict]): + The request object. Message for deleting a workstation + cluster. + name (str): + Required. Name of the workstation + cluster to delete. + + 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.workstations_v1beta.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations + in that region. + + """ + # Create or coerce a protobuf request object. + # Quick 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 workstations.DeleteWorkstationClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.DeleteWorkstationClusterRequest): + request = workstations.DeleteWorkstationClusterRequest(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_workstation_cluster] + + # Certain 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, + workstations.WorkstationCluster, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_workstation_config(self, + request: Optional[Union[workstations.GetWorkstationConfigRequest, 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]] = (), + ) -> workstations.WorkstationConfig: + r"""Returns the requested workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_get_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.GetWorkstationConfigRequest, dict]): + The request object. Request message for + GetWorkstationConfig. + name (str): + Required. Name of the requested + resource. + + 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.workstations_v1beta.types.WorkstationConfig: + A set of configuration options + describing how a workstation will be + run. Workstation configurations are + intended to be shared across multiple + workstations. + + """ + # Create or coerce a protobuf request object. + # Quick 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 workstations.GetWorkstationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.GetWorkstationConfigRequest): + request = workstations.GetWorkstationConfigRequest(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_workstation_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_workstation_configs(self, + request: Optional[Union[workstations.ListWorkstationConfigsRequest, 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.ListWorkstationConfigsPager: + r"""Returns all workstation configurations in the + specified cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_list_workstation_configs(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest, dict]): + The request object. Request message for + ListWorkstationConfigs. + parent (str): + Required. Parent resource name. + 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.workstations_v1beta.services.workstations.pagers.ListWorkstationConfigsPager: + Response message for + ListWorkstationConfigs. + 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 workstations.ListWorkstationConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.ListWorkstationConfigsRequest): + request = workstations.ListWorkstationConfigsRequest(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_workstation_configs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListWorkstationConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_usable_workstation_configs(self, + request: Optional[Union[workstations.ListUsableWorkstationConfigsRequest, 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.ListUsableWorkstationConfigsPager: + r"""Returns all workstation configurations in the + specified cluster on which the caller has the + "workstations.workstation.create" permission. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_list_usable_workstation_configs(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListUsableWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstation_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest, dict]): + The request object. Request message for + ListUsableWorkstationConfigs. + parent (str): + Required. Parent resource name. + 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.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationConfigsPager: + Response message for + ListUsableWorkstationConfigs. + 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 workstations.ListUsableWorkstationConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.ListUsableWorkstationConfigsRequest): + request = workstations.ListUsableWorkstationConfigsRequest(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_usable_workstation_configs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListUsableWorkstationConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_workstation_config(self, + request: Optional[Union[workstations.CreateWorkstationConfigRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation_config: Optional[workstations.WorkstationConfig] = None, + workstation_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_create_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationConfigRequest( + parent="parent_value", + workstation_config_id="workstation_config_id_value", + ) + + # Make the request + operation = client.create_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.CreateWorkstationConfigRequest, dict]): + The request object. Message for creating a + CreateWorkstationConfig. + parent (str): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_config (google.cloud.workstations_v1beta.types.WorkstationConfig): + Required. Config to create. + This corresponds to the ``workstation_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_config_id (str): + Required. ID to use for the + workstation configuration. + + This corresponds to the ``workstation_config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.workstations_v1beta.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. + Workstation configurations are intended to be shared + across multiple workstations. + + """ + # Create or coerce a protobuf request object. + # Quick 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, workstation_config, workstation_config_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a workstations.CreateWorkstationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.CreateWorkstationConfigRequest): + request = workstations.CreateWorkstationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation_config is not None: + request.workstation_config = workstation_config + if workstation_config_id is not None: + request.workstation_config_id = workstation_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_workstation_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # 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, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_workstation_config(self, + request: Optional[Union[workstations.UpdateWorkstationConfigRequest, dict]] = None, + *, + workstation_config: Optional[workstations.WorkstationConfig] = 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 an existing workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_update_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationConfigRequest( + ) + + # Make the request + operation = client.update_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.UpdateWorkstationConfigRequest, dict]): + The request object. Request message for + UpdateWorkstationConfig. + workstation_config (google.cloud.workstations_v1beta.types.WorkstationConfig): + Required. Config to update. + This corresponds to the ``workstation_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask specifying which + fields in the workstation configuration + should 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.workstations_v1beta.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. + Workstation configurations are intended to be shared + across multiple workstations. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a workstations.UpdateWorkstationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.UpdateWorkstationConfigRequest): + request = workstations.UpdateWorkstationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation_config is not None: + request.workstation_config = workstation_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_workstation_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation_config.name", request.workstation_config.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, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_workstation_config(self, + request: Optional[Union[workstations.DeleteWorkstationConfigRequest, 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 the specified workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_delete_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.DeleteWorkstationConfigRequest, dict]): + The request object. Message for deleting a workstation + configuration. + name (str): + Required. Name of the workstation + configuration to delete. + + 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.workstations_v1beta.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. + Workstation configurations are intended to be shared + across multiple workstations. + + """ + # Create or coerce a protobuf request object. + # Quick 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 workstations.DeleteWorkstationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.DeleteWorkstationConfigRequest): + request = workstations.DeleteWorkstationConfigRequest(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_workstation_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # 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, + workstations.WorkstationConfig, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_workstation(self, + request: Optional[Union[workstations.GetWorkstationRequest, 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]] = (), + ) -> workstations.Workstation: + r"""Returns the requested workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_get_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.GetWorkstationRequest, dict]): + The request object. Request message for GetWorkstation. + name (str): + Required. Name of the requested + resource. + + 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.workstations_v1beta.types.Workstation: + A single instance of a developer + workstation with its own persistent + storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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 workstations.GetWorkstationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.GetWorkstationRequest): + request = workstations.GetWorkstationRequest(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_workstation] + + # Certain 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_workstations(self, + request: Optional[Union[workstations.ListWorkstationsRequest, 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.ListWorkstationsPager: + r"""Returns all Workstations using the specified + workstation configuration. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_list_workstations(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.ListWorkstationsRequest, dict]): + The request object. Request message for ListWorkstations. + parent (str): + Required. Parent resource name. + 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.workstations_v1beta.services.workstations.pagers.ListWorkstationsPager: + Response message for + ListWorkstations. + 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 workstations.ListWorkstationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.ListWorkstationsRequest): + request = workstations.ListWorkstationsRequest(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_workstations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListWorkstationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_usable_workstations(self, + request: Optional[Union[workstations.ListUsableWorkstationsRequest, 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.ListUsableWorkstationsPager: + r"""Returns all workstations using the specified + workstation configuration on which the caller has the + "workstations.workstations.use" permission. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_list_usable_workstations(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListUsableWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest, dict]): + The request object. Request message for + ListUsableWorkstations. + parent (str): + Required. Parent resource name. + 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.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationsPager: + Response message for + ListUsableWorkstations. + 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 workstations.ListUsableWorkstationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.ListUsableWorkstationsRequest): + request = workstations.ListUsableWorkstationsRequest(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_usable_workstations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListUsableWorkstationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_workstation(self, + request: Optional[Union[workstations.CreateWorkstationRequest, dict]] = None, + *, + parent: Optional[str] = None, + workstation: Optional[workstations.Workstation] = None, + workstation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_create_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationRequest( + parent="parent_value", + workstation_id="workstation_id_value", + ) + + # Make the request + operation = client.create_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.CreateWorkstationRequest, dict]): + The request object. Message for creating a + CreateWorkstation. + parent (str): + Required. Parent resource name. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation (google.cloud.workstations_v1beta.types.Workstation): + Required. Workstation to create. + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + workstation_id (str): + Required. ID to use for the + workstation. + + This corresponds to the ``workstation_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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, workstation, workstation_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a workstations.CreateWorkstationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.CreateWorkstationRequest): + request = workstations.CreateWorkstationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if workstation is not None: + request.workstation = workstation + if workstation_id is not None: + request.workstation_id = workstation_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_workstation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_workstation(self, + request: Optional[Union[workstations.UpdateWorkstationRequest, dict]] = None, + *, + workstation: Optional[workstations.Workstation] = 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 an existing workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_update_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationRequest( + ) + + # Make the request + operation = client.update_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.UpdateWorkstationRequest, dict]): + The request object. Request message for + UpdateWorkstation. + workstation (google.cloud.workstations_v1beta.types.Workstation): + Required. Workstation to update. + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask specifying which + fields in the workstation configuration + should 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.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation, 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 workstations.UpdateWorkstationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.UpdateWorkstationRequest): + request = workstations.UpdateWorkstationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation is not None: + request.workstation = workstation + 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_workstation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation.name", request.workstation.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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_workstation(self, + request: Optional[Union[workstations.DeleteWorkstationRequest, 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 the specified workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_delete_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.DeleteWorkstationRequest, dict]): + The request object. Request message for + DeleteWorkstation. + name (str): + Required. Name of the workstation to + delete. + + 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.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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 workstations.DeleteWorkstationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.DeleteWorkstationRequest): + request = workstations.DeleteWorkstationRequest(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_workstation] + + # Certain 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def start_workstation(self, + request: Optional[Union[workstations.StartWorkstationRequest, 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"""Starts running a workstation so that users can + connect to 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 workstations_v1beta + + def sample_start_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.StartWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.start_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.StartWorkstationRequest, dict]): + The request object. Request message for StartWorkstation. + name (str): + Required. Name of the workstation to + start. + + 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.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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 workstations.StartWorkstationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.StartWorkstationRequest): + request = workstations.StartWorkstationRequest(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.start_workstation] + + # Certain 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def stop_workstation(self, + request: Optional[Union[workstations.StopWorkstationRequest, 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"""Stops running a workstation, reducing costs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_stop_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.StopWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.StopWorkstationRequest, dict]): + The request object. Request message for StopWorkstation. + name (str): + Required. Name of the workstation to + stop. + + 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.workstations_v1beta.types.Workstation` + A single instance of a developer workstation with its + own persistent storage. + + """ + # Create or coerce a protobuf request object. + # Quick 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 workstations.StopWorkstationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.StopWorkstationRequest): + request = workstations.StopWorkstationRequest(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.stop_workstation] + + # Certain 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, + workstations.Workstation, + metadata_type=workstations.OperationMetadata, + ) + + # Done; return the response. + return response + + def generate_access_token(self, + request: Optional[Union[workstations.GenerateAccessTokenRequest, dict]] = None, + *, + workstation: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> workstations.GenerateAccessTokenResponse: + r"""Returns a short-lived credential that can be used to + send authenticated and authorized traffic to a + workstation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import workstations_v1beta + + def sample_generate_access_token(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.GenerateAccessTokenRequest( + workstation="workstation_value", + ) + + # Make the request + response = client.generate_access_token(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.workstations_v1beta.types.GenerateAccessTokenRequest, dict]): + The request object. Request message for + GenerateAccessToken. + workstation (str): + Required. Name of the workstation for + which the access token should be + generated. + + This corresponds to the ``workstation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.workstations_v1beta.types.GenerateAccessTokenResponse: + Response message for + GenerateAccessToken. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([workstation]) + if request is 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 workstations.GenerateAccessTokenRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, workstations.GenerateAccessTokenRequest): + request = workstations.GenerateAccessTokenRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if workstation is not None: + request.workstation = workstation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_access_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("workstation", request.workstation), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "WorkstationsClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "WorkstationsClient", +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/pagers.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/pagers.py new file mode 100644 index 000000000000..af615b450476 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/pagers.py @@ -0,0 +1,623 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.workstations_v1beta.types import workstations + + +class ListWorkstationClustersPager: + """A pager for iterating through ``list_workstation_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstation_clusters`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWorkstationClusters`` requests and continue to iterate + through the ``workstation_clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse` + 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[..., workstations.ListWorkstationClustersResponse], + request: workstations.ListWorkstationClustersRequest, + response: workstations.ListWorkstationClustersResponse, + *, + 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.workstations_v1beta.types.ListWorkstationClustersRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse): + 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 = workstations.ListWorkstationClustersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[workstations.ListWorkstationClustersResponse]: + 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[workstations.WorkstationCluster]: + for page in self.pages: + yield from page.workstation_clusters + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationClustersAsyncPager: + """A pager for iterating through ``list_workstation_clusters`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstation_clusters`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWorkstationClusters`` requests and continue to iterate + through the ``workstation_clusters`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse` + 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[workstations.ListWorkstationClustersResponse]], + request: workstations.ListWorkstationClustersRequest, + response: workstations.ListWorkstationClustersResponse, + *, + 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.workstations_v1beta.types.ListWorkstationClustersRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse): + 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 = workstations.ListWorkstationClustersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[workstations.ListWorkstationClustersResponse]: + 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[workstations.WorkstationCluster]: + async def async_generator(): + async for page in self.pages: + for response in page.workstation_clusters: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationConfigsPager: + """A pager for iterating through ``list_workstation_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstation_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWorkstationConfigs`` requests and continue to iterate + through the ``workstation_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse` + 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[..., workstations.ListWorkstationConfigsResponse], + request: workstations.ListWorkstationConfigsRequest, + response: workstations.ListWorkstationConfigsResponse, + *, + 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.workstations_v1beta.types.ListWorkstationConfigsRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse): + 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 = workstations.ListWorkstationConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[workstations.ListWorkstationConfigsResponse]: + 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[workstations.WorkstationConfig]: + for page in self.pages: + yield from page.workstation_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationConfigsAsyncPager: + """A pager for iterating through ``list_workstation_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstation_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWorkstationConfigs`` requests and continue to iterate + through the ``workstation_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse` + 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[workstations.ListWorkstationConfigsResponse]], + request: workstations.ListWorkstationConfigsRequest, + response: workstations.ListWorkstationConfigsResponse, + *, + 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.workstations_v1beta.types.ListWorkstationConfigsRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse): + 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 = workstations.ListWorkstationConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[workstations.ListWorkstationConfigsResponse]: + 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[workstations.WorkstationConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.workstation_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsableWorkstationConfigsPager: + """A pager for iterating through ``list_usable_workstation_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstation_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUsableWorkstationConfigs`` requests and continue to iterate + through the ``workstation_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse` + 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[..., workstations.ListUsableWorkstationConfigsResponse], + request: workstations.ListUsableWorkstationConfigsRequest, + response: workstations.ListUsableWorkstationConfigsResponse, + *, + 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.workstations_v1beta.types.ListUsableWorkstationConfigsRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse): + 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 = workstations.ListUsableWorkstationConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[workstations.ListUsableWorkstationConfigsResponse]: + 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[workstations.WorkstationConfig]: + for page in self.pages: + yield from page.workstation_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsableWorkstationConfigsAsyncPager: + """A pager for iterating through ``list_usable_workstation_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstation_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUsableWorkstationConfigs`` requests and continue to iterate + through the ``workstation_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse` + 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[workstations.ListUsableWorkstationConfigsResponse]], + request: workstations.ListUsableWorkstationConfigsRequest, + response: workstations.ListUsableWorkstationConfigsResponse, + *, + 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.workstations_v1beta.types.ListUsableWorkstationConfigsRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse): + 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 = workstations.ListUsableWorkstationConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[workstations.ListUsableWorkstationConfigsResponse]: + 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[workstations.WorkstationConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.workstation_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationsPager: + """A pager for iterating through ``list_workstations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListWorkstationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWorkstations`` requests and continue to iterate + through the ``workstations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationsResponse` + 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[..., workstations.ListWorkstationsResponse], + request: workstations.ListWorkstationsRequest, + response: workstations.ListWorkstationsResponse, + *, + 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.workstations_v1beta.types.ListWorkstationsRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListWorkstationsResponse): + 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 = workstations.ListWorkstationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[workstations.ListWorkstationsResponse]: + 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[workstations.Workstation]: + for page in self.pages: + yield from page.workstations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkstationsAsyncPager: + """A pager for iterating through ``list_workstations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListWorkstationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWorkstations`` requests and continue to iterate + through the ``workstations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationsResponse` + 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[workstations.ListWorkstationsResponse]], + request: workstations.ListWorkstationsRequest, + response: workstations.ListWorkstationsResponse, + *, + 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.workstations_v1beta.types.ListWorkstationsRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListWorkstationsResponse): + 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 = workstations.ListWorkstationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[workstations.ListWorkstationsResponse]: + 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[workstations.Workstation]: + async def async_generator(): + async for page in self.pages: + for response in page.workstations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsableWorkstationsPager: + """A pager for iterating through ``list_usable_workstations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workstations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUsableWorkstations`` requests and continue to iterate + through the ``workstations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse` + 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[..., workstations.ListUsableWorkstationsResponse], + request: workstations.ListUsableWorkstationsRequest, + response: workstations.ListUsableWorkstationsResponse, + *, + 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.workstations_v1beta.types.ListUsableWorkstationsRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse): + 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 = workstations.ListUsableWorkstationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[workstations.ListUsableWorkstationsResponse]: + 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[workstations.Workstation]: + for page in self.pages: + yield from page.workstations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsableWorkstationsAsyncPager: + """A pager for iterating through ``list_usable_workstations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workstations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUsableWorkstations`` requests and continue to iterate + through the ``workstations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse` + 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[workstations.ListUsableWorkstationsResponse]], + request: workstations.ListUsableWorkstationsRequest, + response: workstations.ListUsableWorkstationsResponse, + *, + 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.workstations_v1beta.types.ListUsableWorkstationsRequest): + The initial request object. + response (google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse): + 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 = workstations.ListUsableWorkstationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[workstations.ListUsableWorkstationsResponse]: + 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[workstations.Workstation]: + async def async_generator(): + async for page in self.pages: + for response in page.workstations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/__init__.py new file mode 100644 index 000000000000..fc931d51cd5e --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 WorkstationsTransport +from .grpc import WorkstationsGrpcTransport +from .grpc_asyncio import WorkstationsGrpcAsyncIOTransport +from .rest import WorkstationsRestTransport +from .rest import WorkstationsRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[WorkstationsTransport]] +_transport_registry['grpc'] = WorkstationsGrpcTransport +_transport_registry['grpc_asyncio'] = WorkstationsGrpcAsyncIOTransport +_transport_registry['rest'] = WorkstationsRestTransport + +__all__ = ( + 'WorkstationsTransport', + 'WorkstationsGrpcTransport', + 'WorkstationsGrpcAsyncIOTransport', + 'WorkstationsRestTransport', + 'WorkstationsRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/base.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/base.py new file mode 100644 index 000000000000..9acf0ecb73c3 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/base.py @@ -0,0 +1,545 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.workstations_v1beta 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.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1beta.types import workstations +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 +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class WorkstationsTransport(abc.ABC): + """Abstract transport class for Workstations.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'workstations.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_workstation_cluster: gapic_v1.method.wrap_method( + self.get_workstation_cluster, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_workstation_clusters: gapic_v1.method.wrap_method( + self.list_workstation_clusters, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_workstation_cluster: gapic_v1.method.wrap_method( + self.create_workstation_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.update_workstation_cluster: gapic_v1.method.wrap_method( + self.update_workstation_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_workstation_cluster: gapic_v1.method.wrap_method( + self.delete_workstation_cluster, + default_timeout=60.0, + client_info=client_info, + ), + self.get_workstation_config: gapic_v1.method.wrap_method( + self.get_workstation_config, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_workstation_configs: gapic_v1.method.wrap_method( + self.list_workstation_configs, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_usable_workstation_configs: gapic_v1.method.wrap_method( + self.list_usable_workstation_configs, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_workstation_config: gapic_v1.method.wrap_method( + self.create_workstation_config, + default_timeout=60.0, + client_info=client_info, + ), + self.update_workstation_config: gapic_v1.method.wrap_method( + self.update_workstation_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_workstation_config: gapic_v1.method.wrap_method( + self.delete_workstation_config, + default_timeout=60.0, + client_info=client_info, + ), + self.get_workstation: gapic_v1.method.wrap_method( + self.get_workstation, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_workstations: gapic_v1.method.wrap_method( + self.list_workstations, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_usable_workstations: gapic_v1.method.wrap_method( + self.list_usable_workstations, + default_retry=retries.Retry( +initial=1.0,maximum=10.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_workstation: gapic_v1.method.wrap_method( + self.create_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.update_workstation: gapic_v1.method.wrap_method( + self.update_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_workstation: gapic_v1.method.wrap_method( + self.delete_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.start_workstation: gapic_v1.method.wrap_method( + self.start_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.stop_workstation: gapic_v1.method.wrap_method( + self.stop_workstation, + default_timeout=60.0, + client_info=client_info, + ), + self.generate_access_token: gapic_v1.method.wrap_method( + self.generate_access_token, + default_retry=retries.Retry( +initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + 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 get_workstation_cluster(self) -> Callable[ + [workstations.GetWorkstationClusterRequest], + Union[ + workstations.WorkstationCluster, + Awaitable[workstations.WorkstationCluster] + ]]: + raise NotImplementedError() + + @property + def list_workstation_clusters(self) -> Callable[ + [workstations.ListWorkstationClustersRequest], + Union[ + workstations.ListWorkstationClustersResponse, + Awaitable[workstations.ListWorkstationClustersResponse] + ]]: + raise NotImplementedError() + + @property + def create_workstation_cluster(self) -> Callable[ + [workstations.CreateWorkstationClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_workstation_cluster(self) -> Callable[ + [workstations.UpdateWorkstationClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_workstation_cluster(self) -> Callable[ + [workstations.DeleteWorkstationClusterRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_workstation_config(self) -> Callable[ + [workstations.GetWorkstationConfigRequest], + Union[ + workstations.WorkstationConfig, + Awaitable[workstations.WorkstationConfig] + ]]: + raise NotImplementedError() + + @property + def list_workstation_configs(self) -> Callable[ + [workstations.ListWorkstationConfigsRequest], + Union[ + workstations.ListWorkstationConfigsResponse, + Awaitable[workstations.ListWorkstationConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def list_usable_workstation_configs(self) -> Callable[ + [workstations.ListUsableWorkstationConfigsRequest], + Union[ + workstations.ListUsableWorkstationConfigsResponse, + Awaitable[workstations.ListUsableWorkstationConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def create_workstation_config(self) -> Callable[ + [workstations.CreateWorkstationConfigRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_workstation_config(self) -> Callable[ + [workstations.UpdateWorkstationConfigRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_workstation_config(self) -> Callable[ + [workstations.DeleteWorkstationConfigRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_workstation(self) -> Callable[ + [workstations.GetWorkstationRequest], + Union[ + workstations.Workstation, + Awaitable[workstations.Workstation] + ]]: + raise NotImplementedError() + + @property + def list_workstations(self) -> Callable[ + [workstations.ListWorkstationsRequest], + Union[ + workstations.ListWorkstationsResponse, + Awaitable[workstations.ListWorkstationsResponse] + ]]: + raise NotImplementedError() + + @property + def list_usable_workstations(self) -> Callable[ + [workstations.ListUsableWorkstationsRequest], + Union[ + workstations.ListUsableWorkstationsResponse, + Awaitable[workstations.ListUsableWorkstationsResponse] + ]]: + raise NotImplementedError() + + @property + def create_workstation(self) -> Callable[ + [workstations.CreateWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_workstation(self) -> Callable[ + [workstations.UpdateWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_workstation(self) -> Callable[ + [workstations.DeleteWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def start_workstation(self) -> Callable[ + [workstations.StartWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def stop_workstation(self) -> Callable[ + [workstations.StopWorkstationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def generate_access_token(self) -> Callable[ + [workstations.GenerateAccessTokenRequest], + Union[ + workstations.GenerateAccessTokenResponse, + Awaitable[workstations.GenerateAccessTokenResponse] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'WorkstationsTransport', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc.py new file mode 100644 index 000000000000..0d74bc29c385 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc.py @@ -0,0 +1,943 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1beta.types import workstations +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 +from google.longrunning import operations_pb2 # type: ignore +from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO + + +class WorkstationsGrpcTransport(WorkstationsTransport): + """gRPC backend transport for Workstations. + + Service for interacting with Cloud Workstations. + + 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 = 'workstations.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 = 'workstations.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_workstation_cluster(self) -> Callable[ + [workstations.GetWorkstationClusterRequest], + workstations.WorkstationCluster]: + r"""Return a callable for the get workstation cluster method over gRPC. + + Returns the requested workstation cluster. + + Returns: + Callable[[~.GetWorkstationClusterRequest], + ~.WorkstationCluster]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: + self._stubs['get_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/GetWorkstationCluster', + request_serializer=workstations.GetWorkstationClusterRequest.serialize, + response_deserializer=workstations.WorkstationCluster.deserialize, + ) + return self._stubs['get_workstation_cluster'] + + @property + def list_workstation_clusters(self) -> Callable[ + [workstations.ListWorkstationClustersRequest], + workstations.ListWorkstationClustersResponse]: + r"""Return a callable for the list workstation clusters method over gRPC. + + Returns all workstation clusters in the specified + location. + + Returns: + Callable[[~.ListWorkstationClustersRequest], + ~.ListWorkstationClustersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_clusters' not in self._stubs: + self._stubs['list_workstation_clusters'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListWorkstationClusters', + request_serializer=workstations.ListWorkstationClustersRequest.serialize, + response_deserializer=workstations.ListWorkstationClustersResponse.deserialize, + ) + return self._stubs['list_workstation_clusters'] + + @property + def create_workstation_cluster(self) -> Callable[ + [workstations.CreateWorkstationClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the create workstation cluster method over gRPC. + + Creates a new workstation cluster. + + Returns: + Callable[[~.CreateWorkstationClusterRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: + self._stubs['create_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/CreateWorkstationCluster', + request_serializer=workstations.CreateWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation_cluster'] + + @property + def update_workstation_cluster(self) -> Callable[ + [workstations.UpdateWorkstationClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the update workstation cluster method over gRPC. + + Updates an existing workstation cluster. + + Returns: + Callable[[~.UpdateWorkstationClusterRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: + self._stubs['update_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstationCluster', + request_serializer=workstations.UpdateWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation_cluster'] + + @property + def delete_workstation_cluster(self) -> Callable[ + [workstations.DeleteWorkstationClusterRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete workstation cluster method over gRPC. + + Deletes the specified workstation cluster. + + Returns: + Callable[[~.DeleteWorkstationClusterRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: + self._stubs['delete_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstationCluster', + request_serializer=workstations.DeleteWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation_cluster'] + + @property + def get_workstation_config(self) -> Callable[ + [workstations.GetWorkstationConfigRequest], + workstations.WorkstationConfig]: + r"""Return a callable for the get workstation config method over gRPC. + + Returns the requested workstation configuration. + + Returns: + Callable[[~.GetWorkstationConfigRequest], + ~.WorkstationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: + self._stubs['get_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/GetWorkstationConfig', + request_serializer=workstations.GetWorkstationConfigRequest.serialize, + response_deserializer=workstations.WorkstationConfig.deserialize, + ) + return self._stubs['get_workstation_config'] + + @property + def list_workstation_configs(self) -> Callable[ + [workstations.ListWorkstationConfigsRequest], + workstations.ListWorkstationConfigsResponse]: + r"""Return a callable for the list workstation configs method over gRPC. + + Returns all workstation configurations in the + specified cluster. + + Returns: + Callable[[~.ListWorkstationConfigsRequest], + ~.ListWorkstationConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_configs' not in self._stubs: + self._stubs['list_workstation_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListWorkstationConfigs', + request_serializer=workstations.ListWorkstationConfigsRequest.serialize, + response_deserializer=workstations.ListWorkstationConfigsResponse.deserialize, + ) + return self._stubs['list_workstation_configs'] + + @property + def list_usable_workstation_configs(self) -> Callable[ + [workstations.ListUsableWorkstationConfigsRequest], + workstations.ListUsableWorkstationConfigsResponse]: + r"""Return a callable for the list usable workstation + configs method over gRPC. + + Returns all workstation configurations in the + specified cluster on which the caller has the + "workstations.workstation.create" permission. + + Returns: + Callable[[~.ListUsableWorkstationConfigsRequest], + ~.ListUsableWorkstationConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_usable_workstation_configs' not in self._stubs: + self._stubs['list_usable_workstation_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListUsableWorkstationConfigs', + request_serializer=workstations.ListUsableWorkstationConfigsRequest.serialize, + response_deserializer=workstations.ListUsableWorkstationConfigsResponse.deserialize, + ) + return self._stubs['list_usable_workstation_configs'] + + @property + def create_workstation_config(self) -> Callable[ + [workstations.CreateWorkstationConfigRequest], + operations_pb2.Operation]: + r"""Return a callable for the create workstation config method over gRPC. + + Creates a new workstation configuration. + + Returns: + Callable[[~.CreateWorkstationConfigRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: + self._stubs['create_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/CreateWorkstationConfig', + request_serializer=workstations.CreateWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation_config'] + + @property + def update_workstation_config(self) -> Callable[ + [workstations.UpdateWorkstationConfigRequest], + operations_pb2.Operation]: + r"""Return a callable for the update workstation config method over gRPC. + + Updates an existing workstation configuration. + + Returns: + Callable[[~.UpdateWorkstationConfigRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: + self._stubs['update_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstationConfig', + request_serializer=workstations.UpdateWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation_config'] + + @property + def delete_workstation_config(self) -> Callable[ + [workstations.DeleteWorkstationConfigRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete workstation config method over gRPC. + + Deletes the specified workstation configuration. + + Returns: + Callable[[~.DeleteWorkstationConfigRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: + self._stubs['delete_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstationConfig', + request_serializer=workstations.DeleteWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation_config'] + + @property + def get_workstation(self) -> Callable[ + [workstations.GetWorkstationRequest], + workstations.Workstation]: + r"""Return a callable for the get workstation method over gRPC. + + Returns the requested workstation. + + Returns: + Callable[[~.GetWorkstationRequest], + ~.Workstation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation' not in self._stubs: + self._stubs['get_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/GetWorkstation', + request_serializer=workstations.GetWorkstationRequest.serialize, + response_deserializer=workstations.Workstation.deserialize, + ) + return self._stubs['get_workstation'] + + @property + def list_workstations(self) -> Callable[ + [workstations.ListWorkstationsRequest], + workstations.ListWorkstationsResponse]: + r"""Return a callable for the list workstations method over gRPC. + + Returns all Workstations using the specified + workstation configuration. + + Returns: + Callable[[~.ListWorkstationsRequest], + ~.ListWorkstationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstations' not in self._stubs: + self._stubs['list_workstations'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListWorkstations', + request_serializer=workstations.ListWorkstationsRequest.serialize, + response_deserializer=workstations.ListWorkstationsResponse.deserialize, + ) + return self._stubs['list_workstations'] + + @property + def list_usable_workstations(self) -> Callable[ + [workstations.ListUsableWorkstationsRequest], + workstations.ListUsableWorkstationsResponse]: + r"""Return a callable for the list usable workstations method over gRPC. + + Returns all workstations using the specified + workstation configuration on which the caller has the + "workstations.workstations.use" permission. + + Returns: + Callable[[~.ListUsableWorkstationsRequest], + ~.ListUsableWorkstationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_usable_workstations' not in self._stubs: + self._stubs['list_usable_workstations'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListUsableWorkstations', + request_serializer=workstations.ListUsableWorkstationsRequest.serialize, + response_deserializer=workstations.ListUsableWorkstationsResponse.deserialize, + ) + return self._stubs['list_usable_workstations'] + + @property + def create_workstation(self) -> Callable[ + [workstations.CreateWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the create workstation method over gRPC. + + Creates a new workstation. + + Returns: + Callable[[~.CreateWorkstationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation' not in self._stubs: + self._stubs['create_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/CreateWorkstation', + request_serializer=workstations.CreateWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation'] + + @property + def update_workstation(self) -> Callable[ + [workstations.UpdateWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the update workstation method over gRPC. + + Updates an existing workstation. + + Returns: + Callable[[~.UpdateWorkstationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation' not in self._stubs: + self._stubs['update_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstation', + request_serializer=workstations.UpdateWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation'] + + @property + def delete_workstation(self) -> Callable[ + [workstations.DeleteWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete workstation method over gRPC. + + Deletes the specified workstation. + + Returns: + Callable[[~.DeleteWorkstationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation' not in self._stubs: + self._stubs['delete_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstation', + request_serializer=workstations.DeleteWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation'] + + @property + def start_workstation(self) -> Callable[ + [workstations.StartWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the start workstation method over gRPC. + + Starts running a workstation so that users can + connect to it. + + Returns: + Callable[[~.StartWorkstationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_workstation' not in self._stubs: + self._stubs['start_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/StartWorkstation', + request_serializer=workstations.StartWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['start_workstation'] + + @property + def stop_workstation(self) -> Callable[ + [workstations.StopWorkstationRequest], + operations_pb2.Operation]: + r"""Return a callable for the stop workstation method over gRPC. + + Stops running a workstation, reducing costs. + + Returns: + Callable[[~.StopWorkstationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_workstation' not in self._stubs: + self._stubs['stop_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/StopWorkstation', + request_serializer=workstations.StopWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['stop_workstation'] + + @property + def generate_access_token(self) -> Callable[ + [workstations.GenerateAccessTokenRequest], + workstations.GenerateAccessTokenResponse]: + r"""Return a callable for the generate access token method over gRPC. + + Returns a short-lived credential that can be used to + send authenticated and authorized traffic to a + workstation. + + Returns: + Callable[[~.GenerateAccessTokenRequest], + ~.GenerateAccessTokenResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_access_token' not in self._stubs: + self._stubs['generate_access_token'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/GenerateAccessToken', + request_serializer=workstations.GenerateAccessTokenRequest.serialize, + response_deserializer=workstations.GenerateAccessTokenResponse.deserialize, + ) + return self._stubs['generate_access_token'] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'WorkstationsGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc_asyncio.py new file mode 100644 index 000000000000..14724fe951e7 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc_asyncio.py @@ -0,0 +1,942 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.location import locations_pb2 # type: ignore +from google.cloud.workstations_v1beta.types import workstations +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 +from google.longrunning import operations_pb2 # type: ignore +from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO +from .grpc import WorkstationsGrpcTransport + + +class WorkstationsGrpcAsyncIOTransport(WorkstationsTransport): + """gRPC AsyncIO backend transport for Workstations. + + Service for interacting with Cloud Workstations. + + 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 = 'workstations.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 = 'workstations.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_workstation_cluster(self) -> Callable[ + [workstations.GetWorkstationClusterRequest], + Awaitable[workstations.WorkstationCluster]]: + r"""Return a callable for the get workstation cluster method over gRPC. + + Returns the requested workstation cluster. + + Returns: + Callable[[~.GetWorkstationClusterRequest], + Awaitable[~.WorkstationCluster]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: + self._stubs['get_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/GetWorkstationCluster', + request_serializer=workstations.GetWorkstationClusterRequest.serialize, + response_deserializer=workstations.WorkstationCluster.deserialize, + ) + return self._stubs['get_workstation_cluster'] + + @property + def list_workstation_clusters(self) -> Callable[ + [workstations.ListWorkstationClustersRequest], + Awaitable[workstations.ListWorkstationClustersResponse]]: + r"""Return a callable for the list workstation clusters method over gRPC. + + Returns all workstation clusters in the specified + location. + + Returns: + Callable[[~.ListWorkstationClustersRequest], + Awaitable[~.ListWorkstationClustersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_clusters' not in self._stubs: + self._stubs['list_workstation_clusters'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListWorkstationClusters', + request_serializer=workstations.ListWorkstationClustersRequest.serialize, + response_deserializer=workstations.ListWorkstationClustersResponse.deserialize, + ) + return self._stubs['list_workstation_clusters'] + + @property + def create_workstation_cluster(self) -> Callable[ + [workstations.CreateWorkstationClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create workstation cluster method over gRPC. + + Creates a new workstation cluster. + + Returns: + Callable[[~.CreateWorkstationClusterRequest], + 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_workstation_cluster' not in self._stubs: + self._stubs['create_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/CreateWorkstationCluster', + request_serializer=workstations.CreateWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation_cluster'] + + @property + def update_workstation_cluster(self) -> Callable[ + [workstations.UpdateWorkstationClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update workstation cluster method over gRPC. + + Updates an existing workstation cluster. + + Returns: + Callable[[~.UpdateWorkstationClusterRequest], + 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_workstation_cluster' not in self._stubs: + self._stubs['update_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstationCluster', + request_serializer=workstations.UpdateWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation_cluster'] + + @property + def delete_workstation_cluster(self) -> Callable[ + [workstations.DeleteWorkstationClusterRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete workstation cluster method over gRPC. + + Deletes the specified workstation cluster. + + Returns: + Callable[[~.DeleteWorkstationClusterRequest], + 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_workstation_cluster' not in self._stubs: + self._stubs['delete_workstation_cluster'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstationCluster', + request_serializer=workstations.DeleteWorkstationClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation_cluster'] + + @property + def get_workstation_config(self) -> Callable[ + [workstations.GetWorkstationConfigRequest], + Awaitable[workstations.WorkstationConfig]]: + r"""Return a callable for the get workstation config method over gRPC. + + Returns the requested workstation configuration. + + Returns: + Callable[[~.GetWorkstationConfigRequest], + Awaitable[~.WorkstationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: + self._stubs['get_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/GetWorkstationConfig', + request_serializer=workstations.GetWorkstationConfigRequest.serialize, + response_deserializer=workstations.WorkstationConfig.deserialize, + ) + return self._stubs['get_workstation_config'] + + @property + def list_workstation_configs(self) -> Callable[ + [workstations.ListWorkstationConfigsRequest], + Awaitable[workstations.ListWorkstationConfigsResponse]]: + r"""Return a callable for the list workstation configs method over gRPC. + + Returns all workstation configurations in the + specified cluster. + + Returns: + Callable[[~.ListWorkstationConfigsRequest], + Awaitable[~.ListWorkstationConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation_configs' not in self._stubs: + self._stubs['list_workstation_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListWorkstationConfigs', + request_serializer=workstations.ListWorkstationConfigsRequest.serialize, + response_deserializer=workstations.ListWorkstationConfigsResponse.deserialize, + ) + return self._stubs['list_workstation_configs'] + + @property + def list_usable_workstation_configs(self) -> Callable[ + [workstations.ListUsableWorkstationConfigsRequest], + Awaitable[workstations.ListUsableWorkstationConfigsResponse]]: + r"""Return a callable for the list usable workstation + configs method over gRPC. + + Returns all workstation configurations in the + specified cluster on which the caller has the + "workstations.workstation.create" permission. + + Returns: + Callable[[~.ListUsableWorkstationConfigsRequest], + Awaitable[~.ListUsableWorkstationConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_usable_workstation_configs' not in self._stubs: + self._stubs['list_usable_workstation_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListUsableWorkstationConfigs', + request_serializer=workstations.ListUsableWorkstationConfigsRequest.serialize, + response_deserializer=workstations.ListUsableWorkstationConfigsResponse.deserialize, + ) + return self._stubs['list_usable_workstation_configs'] + + @property + def create_workstation_config(self) -> Callable[ + [workstations.CreateWorkstationConfigRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create workstation config method over gRPC. + + Creates a new workstation configuration. + + Returns: + Callable[[~.CreateWorkstationConfigRequest], + 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_workstation_config' not in self._stubs: + self._stubs['create_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/CreateWorkstationConfig', + request_serializer=workstations.CreateWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation_config'] + + @property + def update_workstation_config(self) -> Callable[ + [workstations.UpdateWorkstationConfigRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update workstation config method over gRPC. + + Updates an existing workstation configuration. + + Returns: + Callable[[~.UpdateWorkstationConfigRequest], + 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_workstation_config' not in self._stubs: + self._stubs['update_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstationConfig', + request_serializer=workstations.UpdateWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation_config'] + + @property + def delete_workstation_config(self) -> Callable[ + [workstations.DeleteWorkstationConfigRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete workstation config method over gRPC. + + Deletes the specified workstation configuration. + + Returns: + Callable[[~.DeleteWorkstationConfigRequest], + 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_workstation_config' not in self._stubs: + self._stubs['delete_workstation_config'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstationConfig', + request_serializer=workstations.DeleteWorkstationConfigRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation_config'] + + @property + def get_workstation(self) -> Callable[ + [workstations.GetWorkstationRequest], + Awaitable[workstations.Workstation]]: + r"""Return a callable for the get workstation method over gRPC. + + Returns the requested workstation. + + Returns: + Callable[[~.GetWorkstationRequest], + Awaitable[~.Workstation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstation' not in self._stubs: + self._stubs['get_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/GetWorkstation', + request_serializer=workstations.GetWorkstationRequest.serialize, + response_deserializer=workstations.Workstation.deserialize, + ) + return self._stubs['get_workstation'] + + @property + def list_workstations(self) -> Callable[ + [workstations.ListWorkstationsRequest], + Awaitable[workstations.ListWorkstationsResponse]]: + r"""Return a callable for the list workstations method over gRPC. + + Returns all Workstations using the specified + workstation configuration. + + Returns: + Callable[[~.ListWorkstationsRequest], + Awaitable[~.ListWorkstationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workstations' not in self._stubs: + self._stubs['list_workstations'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListWorkstations', + request_serializer=workstations.ListWorkstationsRequest.serialize, + response_deserializer=workstations.ListWorkstationsResponse.deserialize, + ) + return self._stubs['list_workstations'] + + @property + def list_usable_workstations(self) -> Callable[ + [workstations.ListUsableWorkstationsRequest], + Awaitable[workstations.ListUsableWorkstationsResponse]]: + r"""Return a callable for the list usable workstations method over gRPC. + + Returns all workstations using the specified + workstation configuration on which the caller has the + "workstations.workstations.use" permission. + + Returns: + Callable[[~.ListUsableWorkstationsRequest], + Awaitable[~.ListUsableWorkstationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_usable_workstations' not in self._stubs: + self._stubs['list_usable_workstations'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/ListUsableWorkstations', + request_serializer=workstations.ListUsableWorkstationsRequest.serialize, + response_deserializer=workstations.ListUsableWorkstationsResponse.deserialize, + ) + return self._stubs['list_usable_workstations'] + + @property + def create_workstation(self) -> Callable[ + [workstations.CreateWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create workstation method over gRPC. + + Creates a new workstation. + + Returns: + Callable[[~.CreateWorkstationRequest], + 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_workstation' not in self._stubs: + self._stubs['create_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/CreateWorkstation', + request_serializer=workstations.CreateWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_workstation'] + + @property + def update_workstation(self) -> Callable[ + [workstations.UpdateWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update workstation method over gRPC. + + Updates an existing workstation. + + Returns: + Callable[[~.UpdateWorkstationRequest], + 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_workstation' not in self._stubs: + self._stubs['update_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstation', + request_serializer=workstations.UpdateWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_workstation'] + + @property + def delete_workstation(self) -> Callable[ + [workstations.DeleteWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete workstation method over gRPC. + + Deletes the specified workstation. + + Returns: + Callable[[~.DeleteWorkstationRequest], + 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_workstation' not in self._stubs: + self._stubs['delete_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstation', + request_serializer=workstations.DeleteWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_workstation'] + + @property + def start_workstation(self) -> Callable[ + [workstations.StartWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the start workstation method over gRPC. + + Starts running a workstation so that users can + connect to it. + + Returns: + Callable[[~.StartWorkstationRequest], + 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 'start_workstation' not in self._stubs: + self._stubs['start_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/StartWorkstation', + request_serializer=workstations.StartWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['start_workstation'] + + @property + def stop_workstation(self) -> Callable[ + [workstations.StopWorkstationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the stop workstation method over gRPC. + + Stops running a workstation, reducing costs. + + Returns: + Callable[[~.StopWorkstationRequest], + 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 'stop_workstation' not in self._stubs: + self._stubs['stop_workstation'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/StopWorkstation', + request_serializer=workstations.StopWorkstationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['stop_workstation'] + + @property + def generate_access_token(self) -> Callable[ + [workstations.GenerateAccessTokenRequest], + Awaitable[workstations.GenerateAccessTokenResponse]]: + r"""Return a callable for the generate access token method over gRPC. + + Returns a short-lived credential that can be used to + send authenticated and authorized traffic to a + workstation. + + Returns: + Callable[[~.GenerateAccessTokenRequest], + Awaitable[~.GenerateAccessTokenResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_access_token' not in self._stubs: + self._stubs['generate_access_token'] = self.grpc_channel.unary_unary( + '/google.cloud.workstations.v1beta.Workstations/GenerateAccessToken', + request_serializer=workstations.GenerateAccessTokenRequest.serialize, + response_deserializer=workstations.GenerateAccessTokenResponse.deserialize, + ) + return self._stubs['generate_access_token'] + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'WorkstationsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest.py new file mode 100644 index 000000000000..3d49638dac6d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest.py @@ -0,0 +1,3177 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.workstations_v1beta.types import workstations +from google.longrunning import operations_pb2 # type: ignore + +from .base import WorkstationsTransport, 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 WorkstationsRestInterceptor: + """Interceptor for Workstations. + + 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 WorkstationsRestTransport. + + .. code-block:: python + class MyCustomWorkstationsInterceptor(WorkstationsRestInterceptor): + def pre_create_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_workstation_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_workstation_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_workstation_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_workstation_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_workstation_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_workstation_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_workstation_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_workstation_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_access_token(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_access_token(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_workstation_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_workstation_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_workstation_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_workstation_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_usable_workstation_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_usable_workstation_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_usable_workstations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_usable_workstations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_workstation_clusters(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_workstation_clusters(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_workstation_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_workstation_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_workstations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_workstations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_start_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_start_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_stop_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_stop_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_workstation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_workstation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_workstation_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_workstation_cluster(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_workstation_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_workstation_config(self, response): + logging.log(f"Received response: {response}") + return response + + transport = WorkstationsRestTransport(interceptor=MyCustomWorkstationsInterceptor()) + client = WorkstationsClient(transport=transport) + + + """ + def pre_create_workstation(self, request: workstations.CreateWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_create_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_create_workstation_cluster(self, request: workstations.CreateWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_workstation_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_create_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_workstation_cluster + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_create_workstation_config(self, request: workstations.CreateWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_workstation_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_create_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_workstation_config + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_delete_workstation(self, request: workstations.DeleteWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_delete_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_delete_workstation_cluster(self, request: workstations.DeleteWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_workstation_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_delete_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_workstation_cluster + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_delete_workstation_config(self, request: workstations.DeleteWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_workstation_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_delete_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_workstation_config + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_generate_access_token(self, request: workstations.GenerateAccessTokenRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GenerateAccessTokenRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_access_token + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_generate_access_token(self, response: workstations.GenerateAccessTokenResponse) -> workstations.GenerateAccessTokenResponse: + """Post-rpc interceptor for generate_access_token + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_get_workstation(self, request: workstations.GetWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_get_workstation(self, response: workstations.Workstation) -> workstations.Workstation: + """Post-rpc interceptor for get_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_get_workstation_cluster(self, request: workstations.GetWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_workstation_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_get_workstation_cluster(self, response: workstations.WorkstationCluster) -> workstations.WorkstationCluster: + """Post-rpc interceptor for get_workstation_cluster + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_get_workstation_config(self, request: workstations.GetWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_workstation_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_get_workstation_config(self, response: workstations.WorkstationConfig) -> workstations.WorkstationConfig: + """Post-rpc interceptor for get_workstation_config + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_list_usable_workstation_configs(self, request: workstations.ListUsableWorkstationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListUsableWorkstationConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_usable_workstation_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_usable_workstation_configs(self, response: workstations.ListUsableWorkstationConfigsResponse) -> workstations.ListUsableWorkstationConfigsResponse: + """Post-rpc interceptor for list_usable_workstation_configs + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_list_usable_workstations(self, request: workstations.ListUsableWorkstationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListUsableWorkstationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_usable_workstations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_usable_workstations(self, response: workstations.ListUsableWorkstationsResponse) -> workstations.ListUsableWorkstationsResponse: + """Post-rpc interceptor for list_usable_workstations + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_list_workstation_clusters(self, request: workstations.ListWorkstationClustersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationClustersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_workstation_clusters + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_workstation_clusters(self, response: workstations.ListWorkstationClustersResponse) -> workstations.ListWorkstationClustersResponse: + """Post-rpc interceptor for list_workstation_clusters + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_list_workstation_configs(self, request: workstations.ListWorkstationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_workstation_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_workstation_configs(self, response: workstations.ListWorkstationConfigsResponse) -> workstations.ListWorkstationConfigsResponse: + """Post-rpc interceptor for list_workstation_configs + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_list_workstations(self, request: workstations.ListWorkstationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_workstations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_workstations(self, response: workstations.ListWorkstationsResponse) -> workstations.ListWorkstationsResponse: + """Post-rpc interceptor for list_workstations + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_start_workstation(self, request: workstations.StartWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.StartWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for start_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_start_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for start_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_stop_workstation(self, request: workstations.StopWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.StopWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for stop_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_stop_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for stop_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_update_workstation(self, request: workstations.UpdateWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_workstation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_update_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_workstation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_update_workstation_cluster(self, request: workstations.UpdateWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_workstation_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_update_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_workstation_cluster + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_update_workstation_config(self, request: workstations.UpdateWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_workstation_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_update_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_workstation_config + + Override in a subclass to manipulate the response + after it is returned by the Workstations 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 Workstations 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 Workstations 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 Workstations 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 Workstations 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 Workstations 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 Workstations server but before + it is returned to user code. + """ + return response + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Workstations server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Workstations server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class WorkstationsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: WorkstationsRestInterceptor + + +class WorkstationsRestTransport(WorkstationsTransport): + """REST backend transport for Workstations. + + Service for interacting with Cloud Workstations. + + 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 = 'workstations.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[WorkstationsRestInterceptor] = 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 WorkstationsRestInterceptor() + 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.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateWorkstation(WorkstationsRestStub): + def __hash__(self): + return hash("CreateWorkstation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "workstationId" : "", } + + @classmethod + def _get_unset_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: workstations.CreateWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create workstation method over HTTP. + + Args: + request (~.workstations.CreateWorkstationRequest): + The request object. Message for creating a + CreateWorkstation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): 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': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations', + 'body': 'workstation', + }, + ] + request, metadata = self._interceptor.pre_create_workstation(request, metadata) + pb_request = workstations.CreateWorkstationRequest.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_workstation(resp) + return resp + + class _CreateWorkstationCluster(WorkstationsRestStub): + def __hash__(self): + return hash("CreateWorkstationCluster") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "workstationClusterId" : "", } + + @classmethod + def _get_unset_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: workstations.CreateWorkstationClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create workstation + cluster method over HTTP. + + Args: + request (~.workstations.CreateWorkstationClusterRequest): + The request object. Message for creating a + CreateWorkstationCluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): 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': '/v1beta/{parent=projects/*/locations/*}/workstationClusters', + 'body': 'workstation_cluster', + }, + ] + request, metadata = self._interceptor.pre_create_workstation_cluster(request, metadata) + pb_request = workstations.CreateWorkstationClusterRequest.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_workstation_cluster(resp) + return resp + + class _CreateWorkstationConfig(WorkstationsRestStub): + def __hash__(self): + return hash("CreateWorkstationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "workstationConfigId" : "", } + + @classmethod + def _get_unset_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: workstations.CreateWorkstationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create workstation config method over HTTP. + + Args: + request (~.workstations.CreateWorkstationConfigRequest): + The request object. Message for creating a + CreateWorkstationConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): 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': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs', + 'body': 'workstation_config', + }, + ] + request, metadata = self._interceptor.pre_create_workstation_config(request, metadata) + pb_request = workstations.CreateWorkstationConfigRequest.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_workstation_config(resp) + return resp + + class _DeleteWorkstation(WorkstationsRestStub): + def __hash__(self): + return hash("DeleteWorkstation") + + __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: workstations.DeleteWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete workstation method over HTTP. + + Args: + request (~.workstations.DeleteWorkstationRequest): + The request object. Request message for + DeleteWorkstation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_workstation(request, metadata) + pb_request = workstations.DeleteWorkstationRequest.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_workstation(resp) + return resp + + class _DeleteWorkstationCluster(WorkstationsRestStub): + def __hash__(self): + return hash("DeleteWorkstationCluster") + + __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: workstations.DeleteWorkstationClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete workstation + cluster method over HTTP. + + Args: + request (~.workstations.DeleteWorkstationClusterRequest): + The request object. Message for deleting a workstation + cluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_workstation_cluster(request, metadata) + pb_request = workstations.DeleteWorkstationClusterRequest.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_workstation_cluster(resp) + return resp + + class _DeleteWorkstationConfig(WorkstationsRestStub): + def __hash__(self): + return hash("DeleteWorkstationConfig") + + __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: workstations.DeleteWorkstationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete workstation config method over HTTP. + + Args: + request (~.workstations.DeleteWorkstationConfigRequest): + The request object. Message for deleting a workstation + configuration. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_workstation_config(request, metadata) + pb_request = workstations.DeleteWorkstationConfigRequest.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_workstation_config(resp) + return resp + + class _GenerateAccessToken(WorkstationsRestStub): + def __hash__(self): + return hash("GenerateAccessToken") + + __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: workstations.GenerateAccessTokenRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.GenerateAccessTokenResponse: + r"""Call the generate access token method over HTTP. + + Args: + request (~.workstations.GenerateAccessTokenRequest): + The request object. Request message for + GenerateAccessToken. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.workstations.GenerateAccessTokenResponse: + Response message for + GenerateAccessToken. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{workstation=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:generateAccessToken', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_generate_access_token(request, metadata) + pb_request = workstations.GenerateAccessTokenRequest.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 = workstations.GenerateAccessTokenResponse() + pb_resp = workstations.GenerateAccessTokenResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_access_token(resp) + return resp + + class _GetWorkstation(WorkstationsRestStub): + def __hash__(self): + return hash("GetWorkstation") + + __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: workstations.GetWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.Workstation: + r"""Call the get workstation method over HTTP. + + Args: + request (~.workstations.GetWorkstationRequest): + The request object. Request message for GetWorkstation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.workstations.Workstation: + A single instance of a developer + workstation with its own persistent + storage. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', + }, + ] + request, metadata = self._interceptor.pre_get_workstation(request, metadata) + pb_request = workstations.GetWorkstationRequest.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 = workstations.Workstation() + pb_resp = workstations.Workstation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_workstation(resp) + return resp + + class _GetWorkstationCluster(WorkstationsRestStub): + def __hash__(self): + return hash("GetWorkstationCluster") + + __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: workstations.GetWorkstationClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.WorkstationCluster: + r"""Call the get workstation cluster method over HTTP. + + Args: + request (~.workstations.GetWorkstationClusterRequest): + The request object. Request message for + GetWorkstationCluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.workstations.WorkstationCluster: + A grouping of workstation + configurations and the associated + workstations in that region. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/workstationClusters/*}', + }, + ] + request, metadata = self._interceptor.pre_get_workstation_cluster(request, metadata) + pb_request = workstations.GetWorkstationClusterRequest.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 = workstations.WorkstationCluster() + pb_resp = workstations.WorkstationCluster.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_workstation_cluster(resp) + return resp + + class _GetWorkstationConfig(WorkstationsRestStub): + def __hash__(self): + return hash("GetWorkstationConfig") + + __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: workstations.GetWorkstationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.WorkstationConfig: + r"""Call the get workstation config method over HTTP. + + Args: + request (~.workstations.GetWorkstationConfigRequest): + The request object. Request message for + GetWorkstationConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.workstations.WorkstationConfig: + A set of configuration options + describing how a workstation will be + run. Workstation configurations are + intended to be shared across multiple + workstations. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_workstation_config(request, metadata) + pb_request = workstations.GetWorkstationConfigRequest.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 = workstations.WorkstationConfig() + pb_resp = workstations.WorkstationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_workstation_config(resp) + return resp + + class _ListUsableWorkstationConfigs(WorkstationsRestStub): + def __hash__(self): + return hash("ListUsableWorkstationConfigs") + + __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: workstations.ListUsableWorkstationConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListUsableWorkstationConfigsResponse: + r"""Call the list usable workstation + configs method over HTTP. + + Args: + request (~.workstations.ListUsableWorkstationConfigsRequest): + The request object. Request message for + ListUsableWorkstationConfigs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.workstations.ListUsableWorkstationConfigsResponse: + Response message for + ListUsableWorkstationConfigs. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs:listUsable', + }, + ] + request, metadata = self._interceptor.pre_list_usable_workstation_configs(request, metadata) + pb_request = workstations.ListUsableWorkstationConfigsRequest.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 = workstations.ListUsableWorkstationConfigsResponse() + pb_resp = workstations.ListUsableWorkstationConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_usable_workstation_configs(resp) + return resp + + class _ListUsableWorkstations(WorkstationsRestStub): + def __hash__(self): + return hash("ListUsableWorkstations") + + __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: workstations.ListUsableWorkstationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListUsableWorkstationsResponse: + r"""Call the list usable workstations method over HTTP. + + Args: + request (~.workstations.ListUsableWorkstationsRequest): + The request object. Request message for + ListUsableWorkstations. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.workstations.ListUsableWorkstationsResponse: + Response message for + ListUsableWorkstations. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations:listUsable', + }, + ] + request, metadata = self._interceptor.pre_list_usable_workstations(request, metadata) + pb_request = workstations.ListUsableWorkstationsRequest.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 = workstations.ListUsableWorkstationsResponse() + pb_resp = workstations.ListUsableWorkstationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_usable_workstations(resp) + return resp + + class _ListWorkstationClusters(WorkstationsRestStub): + def __hash__(self): + return hash("ListWorkstationClusters") + + __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: workstations.ListWorkstationClustersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListWorkstationClustersResponse: + r"""Call the list workstation clusters method over HTTP. + + Args: + request (~.workstations.ListWorkstationClustersRequest): + The request object. Request message for + ListWorkstationClusters. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.workstations.ListWorkstationClustersResponse: + Response message for + ListWorkstationClusters. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*}/workstationClusters', + }, + ] + request, metadata = self._interceptor.pre_list_workstation_clusters(request, metadata) + pb_request = workstations.ListWorkstationClustersRequest.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 = workstations.ListWorkstationClustersResponse() + pb_resp = workstations.ListWorkstationClustersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_workstation_clusters(resp) + return resp + + class _ListWorkstationConfigs(WorkstationsRestStub): + def __hash__(self): + return hash("ListWorkstationConfigs") + + __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: workstations.ListWorkstationConfigsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListWorkstationConfigsResponse: + r"""Call the list workstation configs method over HTTP. + + Args: + request (~.workstations.ListWorkstationConfigsRequest): + The request object. Request message for + ListWorkstationConfigs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.workstations.ListWorkstationConfigsResponse: + Response message for + ListWorkstationConfigs. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs', + }, + ] + request, metadata = self._interceptor.pre_list_workstation_configs(request, metadata) + pb_request = workstations.ListWorkstationConfigsRequest.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 = workstations.ListWorkstationConfigsResponse() + pb_resp = workstations.ListWorkstationConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_workstation_configs(resp) + return resp + + class _ListWorkstations(WorkstationsRestStub): + def __hash__(self): + return hash("ListWorkstations") + + __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: workstations.ListWorkstationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> workstations.ListWorkstationsResponse: + r"""Call the list workstations method over HTTP. + + Args: + request (~.workstations.ListWorkstationsRequest): + The request object. Request message for ListWorkstations. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.workstations.ListWorkstationsResponse: + Response message for + ListWorkstations. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations', + }, + ] + request, metadata = self._interceptor.pre_list_workstations(request, metadata) + pb_request = workstations.ListWorkstationsRequest.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 = workstations.ListWorkstationsResponse() + pb_resp = workstations.ListWorkstationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_workstations(resp) + return resp + + class _StartWorkstation(WorkstationsRestStub): + def __hash__(self): + return hash("StartWorkstation") + + __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: workstations.StartWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the start workstation method over HTTP. + + Args: + request (~.workstations.StartWorkstationRequest): + The request object. Request message for StartWorkstation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:start', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_start_workstation(request, metadata) + pb_request = workstations.StartWorkstationRequest.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_start_workstation(resp) + return resp + + class _StopWorkstation(WorkstationsRestStub): + def __hash__(self): + return hash("StopWorkstation") + + __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: workstations.StopWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the stop workstation method over HTTP. + + Args: + request (~.workstations.StopWorkstationRequest): + The request object. Request message for StopWorkstation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:stop', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_stop_workstation(request, metadata) + pb_request = workstations.StopWorkstationRequest.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_stop_workstation(resp) + return resp + + class _UpdateWorkstation(WorkstationsRestStub): + def __hash__(self): + return hash("UpdateWorkstation") + + __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: workstations.UpdateWorkstationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update workstation method over HTTP. + + Args: + request (~.workstations.UpdateWorkstationRequest): + The request object. Request message for + UpdateWorkstation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): 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': '/v1beta/{workstation.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', + 'body': 'workstation', + }, + ] + request, metadata = self._interceptor.pre_update_workstation(request, metadata) + pb_request = workstations.UpdateWorkstationRequest.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_workstation(resp) + return resp + + class _UpdateWorkstationCluster(WorkstationsRestStub): + def __hash__(self): + return hash("UpdateWorkstationCluster") + + __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: workstations.UpdateWorkstationClusterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update workstation + cluster method over HTTP. + + Args: + request (~.workstations.UpdateWorkstationClusterRequest): + The request object. Request message for + UpdateWorkstationCluster. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): 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': '/v1beta/{workstation_cluster.name=projects/*/locations/*/workstationClusters/*}', + 'body': 'workstation_cluster', + }, + ] + request, metadata = self._interceptor.pre_update_workstation_cluster(request, metadata) + pb_request = workstations.UpdateWorkstationClusterRequest.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_workstation_cluster(resp) + return resp + + class _UpdateWorkstationConfig(WorkstationsRestStub): + def __hash__(self): + return hash("UpdateWorkstationConfig") + + __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: workstations.UpdateWorkstationConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update workstation config method over HTTP. + + Args: + request (~.workstations.UpdateWorkstationConfigRequest): + The request object. Request message for + UpdateWorkstationConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): 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': '/v1beta/{workstation_config.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', + 'body': 'workstation_config', + }, + ] + request, metadata = self._interceptor.pre_update_workstation_config(request, metadata) + pb_request = workstations.UpdateWorkstationConfigRequest.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_workstation_config(resp) + return resp + + @property + def create_workstation(self) -> Callable[ + [workstations.CreateWorkstationRequest], + 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._CreateWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_workstation_cluster(self) -> Callable[ + [workstations.CreateWorkstationClusterRequest], + 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._CreateWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_workstation_config(self) -> Callable[ + [workstations.CreateWorkstationConfigRequest], + 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._CreateWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_workstation(self) -> Callable[ + [workstations.DeleteWorkstationRequest], + 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._DeleteWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_workstation_cluster(self) -> Callable[ + [workstations.DeleteWorkstationClusterRequest], + 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._DeleteWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_workstation_config(self) -> Callable[ + [workstations.DeleteWorkstationConfigRequest], + 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._DeleteWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_access_token(self) -> Callable[ + [workstations.GenerateAccessTokenRequest], + workstations.GenerateAccessTokenResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateAccessToken(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_workstation(self) -> Callable[ + [workstations.GetWorkstationRequest], + workstations.Workstation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_workstation_cluster(self) -> Callable[ + [workstations.GetWorkstationClusterRequest], + workstations.WorkstationCluster]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_workstation_config(self) -> Callable[ + [workstations.GetWorkstationConfigRequest], + workstations.WorkstationConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_usable_workstation_configs(self) -> Callable[ + [workstations.ListUsableWorkstationConfigsRequest], + workstations.ListUsableWorkstationConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListUsableWorkstationConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_usable_workstations(self) -> Callable[ + [workstations.ListUsableWorkstationsRequest], + workstations.ListUsableWorkstationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListUsableWorkstations(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_workstation_clusters(self) -> Callable[ + [workstations.ListWorkstationClustersRequest], + workstations.ListWorkstationClustersResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListWorkstationClusters(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_workstation_configs(self) -> Callable[ + [workstations.ListWorkstationConfigsRequest], + workstations.ListWorkstationConfigsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListWorkstationConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_workstations(self) -> Callable[ + [workstations.ListWorkstationsRequest], + workstations.ListWorkstationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListWorkstations(self._session, self._host, self._interceptor) # type: ignore + + @property + def start_workstation(self) -> Callable[ + [workstations.StartWorkstationRequest], + 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._StartWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def stop_workstation(self) -> Callable[ + [workstations.StopWorkstationRequest], + 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._StopWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_workstation(self) -> Callable[ + [workstations.UpdateWorkstationRequest], + 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._UpdateWorkstation(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_workstation_cluster(self) -> Callable[ + [workstations.UpdateWorkstationClusterRequest], + 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._UpdateWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_workstation_config(self) -> Callable[ + [workstations.UpdateWorkstationConfigRequest], + 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._UpdateWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(WorkstationsRestStub): + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:getIamPolicy', + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(WorkstationsRestStub): + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:setIamPolicy', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + 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) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(WorkstationsRestStub): + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:testIamPermissions', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + 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) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(WorkstationsRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + 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 self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(WorkstationsRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(WorkstationsRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(WorkstationsRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'WorkstationsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/__init__.py new file mode 100644 index 000000000000..78e68e36bfd4 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/__init__.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .workstations import ( + CreateWorkstationClusterRequest, + CreateWorkstationConfigRequest, + CreateWorkstationRequest, + DeleteWorkstationClusterRequest, + DeleteWorkstationConfigRequest, + DeleteWorkstationRequest, + GenerateAccessTokenRequest, + GenerateAccessTokenResponse, + GetWorkstationClusterRequest, + GetWorkstationConfigRequest, + GetWorkstationRequest, + ListUsableWorkstationConfigsRequest, + ListUsableWorkstationConfigsResponse, + ListUsableWorkstationsRequest, + ListUsableWorkstationsResponse, + ListWorkstationClustersRequest, + ListWorkstationClustersResponse, + ListWorkstationConfigsRequest, + ListWorkstationConfigsResponse, + ListWorkstationsRequest, + ListWorkstationsResponse, + OperationMetadata, + StartWorkstationRequest, + StopWorkstationRequest, + UpdateWorkstationClusterRequest, + UpdateWorkstationConfigRequest, + UpdateWorkstationRequest, + Workstation, + WorkstationCluster, + WorkstationConfig, +) + +__all__ = ( + 'CreateWorkstationClusterRequest', + 'CreateWorkstationConfigRequest', + 'CreateWorkstationRequest', + 'DeleteWorkstationClusterRequest', + 'DeleteWorkstationConfigRequest', + 'DeleteWorkstationRequest', + 'GenerateAccessTokenRequest', + 'GenerateAccessTokenResponse', + 'GetWorkstationClusterRequest', + 'GetWorkstationConfigRequest', + 'GetWorkstationRequest', + 'ListUsableWorkstationConfigsRequest', + 'ListUsableWorkstationConfigsResponse', + 'ListUsableWorkstationsRequest', + 'ListUsableWorkstationsResponse', + 'ListWorkstationClustersRequest', + 'ListWorkstationClustersResponse', + 'ListWorkstationConfigsRequest', + 'ListWorkstationConfigsResponse', + 'ListWorkstationsRequest', + 'ListWorkstationsResponse', + 'OperationMetadata', + 'StartWorkstationRequest', + 'StopWorkstationRequest', + 'UpdateWorkstationClusterRequest', + 'UpdateWorkstationConfigRequest', + 'UpdateWorkstationRequest', + 'Workstation', + 'WorkstationCluster', + 'WorkstationConfig', +) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/workstations.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/workstations.py new file mode 100644 index 000000000000..7d9845c50b8d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/workstations.py @@ -0,0 +1,1793 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.workstations.v1beta', + manifest={ + 'WorkstationCluster', + 'WorkstationConfig', + 'Workstation', + 'GetWorkstationClusterRequest', + 'ListWorkstationClustersRequest', + 'ListWorkstationClustersResponse', + 'CreateWorkstationClusterRequest', + 'UpdateWorkstationClusterRequest', + 'DeleteWorkstationClusterRequest', + 'GetWorkstationConfigRequest', + 'ListWorkstationConfigsRequest', + 'ListWorkstationConfigsResponse', + 'ListUsableWorkstationConfigsRequest', + 'ListUsableWorkstationConfigsResponse', + 'CreateWorkstationConfigRequest', + 'UpdateWorkstationConfigRequest', + 'DeleteWorkstationConfigRequest', + 'GetWorkstationRequest', + 'ListWorkstationsRequest', + 'ListWorkstationsResponse', + 'ListUsableWorkstationsRequest', + 'ListUsableWorkstationsResponse', + 'CreateWorkstationRequest', + 'UpdateWorkstationRequest', + 'DeleteWorkstationRequest', + 'StartWorkstationRequest', + 'StopWorkstationRequest', + 'GenerateAccessTokenRequest', + 'GenerateAccessTokenResponse', + 'OperationMetadata', + }, +) + + +class WorkstationCluster(proto.Message): + r"""A grouping of workstation configurations and the associated + workstations in that region. + + Attributes: + name (str): + Full name of this resource. + display_name (str): + Human-readable name for this resource. + uid (str): + Output only. A system-assigned unique + identified for this resource. + reconciling (bool): + Output only. Indicates whether this resource + is currently being updated to match its intended + state. + annotations (MutableMapping[str, str]): + Client-specified annotations. + labels (MutableMapping[str, str]): + Client-specified labels that are applied to + the resource and that are also propagated to the + underlying Compute Engine resources. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this resource was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this resource was most + recently updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this resource was + soft-deleted. + etag (str): + Checksum computed by the server. May be sent + on update and delete requests to make sure that + the client has an up-to-date value before + proceeding. + network (str): + Immutable. Name of the Compute Engine network + in which instances associated with this cluster + will be created. + subnetwork (str): + Immutable. Name of the Compute Engine + subnetwork in which instances associated with + this cluster will be created. Must be part of + the subnetwork specified for this cluster. + control_plane_ip (str): + Output only. The private IP address of the + control plane for this cluster. Workstation VMs + need access to this IP address to work with the + service, so make sure that your firewall rules + allow egress from the workstation VMs to this + address. + private_cluster_config (google.cloud.workstations_v1beta.types.WorkstationCluster.PrivateClusterConfig): + Configuration for private cluster. + degraded (bool): + Output only. Whether this resource is in degraded mode, in + which case it may require user action to restore full + functionality. Details can be found in the ``conditions`` + field. + conditions (MutableSequence[google.rpc.status_pb2.Status]): + Output only. Status conditions describing the + current resource state. + """ + + class PrivateClusterConfig(proto.Message): + r"""Configuration options for private clusters. + + Attributes: + enable_private_endpoint (bool): + Immutable. Whether Workstations endpoint is + private. + cluster_hostname (str): + Output only. Hostname for the workstation + cluster. This field will be populated only when + private endpoint is enabled. To access + workstations in the cluster, create a new DNS + zone mapping this domain name to an internal IP + address and a forwarding rule mapping that + address to the service attachment. + service_attachment_uri (str): + Output only. Service attachment URI for the workstation + cluster. The service attachemnt is created when private + endpoint is enabled. To access workstations in the cluster, + configure access to the managed service using `Private + Service + Connect `__. + allowed_projects (MutableSequence[str]): + Additional projects that are allowed to + attach to the workstation cluster's service + attachment. By default, the workstation + cluster's project and the VPC host project (if + different) are allowed. + """ + + enable_private_endpoint: bool = proto.Field( + proto.BOOL, + number=1, + ) + cluster_hostname: str = proto.Field( + proto.STRING, + number=2, + ) + service_attachment_uri: str = proto.Field( + proto.STRING, + number=3, + ) + allowed_projects: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=15, + ) + 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, + ) + network: str = proto.Field( + proto.STRING, + number=10, + ) + subnetwork: str = proto.Field( + proto.STRING, + number=11, + ) + control_plane_ip: str = proto.Field( + proto.STRING, + number=16, + ) + private_cluster_config: PrivateClusterConfig = proto.Field( + proto.MESSAGE, + number=12, + message=PrivateClusterConfig, + ) + degraded: bool = proto.Field( + proto.BOOL, + number=13, + ) + conditions: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=status_pb2.Status, + ) + + +class WorkstationConfig(proto.Message): + r"""A set of configuration options describing how a workstation + will be run. Workstation configurations are intended to be + shared across multiple workstations. + + Attributes: + name (str): + Full name of this resource. + display_name (str): + Human-readable name for this resource. + uid (str): + Output only. A system-assigned unique + identified for this resource. + reconciling (bool): + Output only. Indicates whether this resource + is currently being updated to match its intended + state. + annotations (MutableMapping[str, str]): + Client-specified annotations. + labels (MutableMapping[str, str]): + Client-specified labels that are applied to + the resource and that are also propagated to the + underlying Compute Engine resources. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this resource was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this resource was most + recently updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this resource was + soft-deleted. + etag (str): + Checksum computed by the server. May be sent + on update and delete requests to make sure that + the client has an up-to-date value before + proceeding. + idle_timeout (google.protobuf.duration_pb2.Duration): + How long to wait before automatically + stopping an instance that hasn't received any + user traffic. A value of 0 indicates that this + instance should never time out due to idleness. + Defaults to 20 minutes. + running_timeout (google.protobuf.duration_pb2.Duration): + How long to wait before automatically stopping a workstation + after it started. A value of 0 indicates that workstations + using this configuration should never time out. Must be + greater than 0 and less than 24 hours if encryption_key is + set. Defaults to 12 hours. + host (google.cloud.workstations_v1beta.types.WorkstationConfig.Host): + Runtime host for the workstation. + persistent_directories (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig.PersistentDirectory]): + Directories to persist across workstation + sessions. + container (google.cloud.workstations_v1beta.types.WorkstationConfig.Container): + Container that will be run for each + workstation using this configuration when that + workstation is started. + encryption_key (google.cloud.workstations_v1beta.types.WorkstationConfig.CustomerEncryptionKey): + Immutable. Encrypts resources of this + workstation configuration using a + customer-managed encryption key. + If specified, the boot disk of the Compute + Engine instance and the persistent disk are + encrypted using this encryption key. If this + field is not set, the disks are encrypted using + a generated key. Customer-managed encryption + keys do not protect disk metadata. + If the customer-managed encryption key is + rotated, when the workstation instance is + stopped, the system attempts to recreate the + persistent disk with the new version of the key. + Be sure to keep older versions of the key until + the persistent disk is recreated. Otherwise, + data on the persistent disk will be lost. + If the encryption key is revoked, the + workstation session will automatically be + stopped within 7 hours. + + Immutable after the workstation configuration is + created. + readiness_checks (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig.ReadinessCheck]): + Readiness checks to perform when starting a + workstation using this workstation + configuration. Mark a workstation as running + only after all specified readiness checks return + 200 status codes. + degraded (bool): + Output only. Whether this resource is in degraded mode, in + which case it may require user action to restore full + functionality. Details can be found in the ``conditions`` + field. + conditions (MutableSequence[google.rpc.status_pb2.Status]): + Output only. Status conditions describing the + current resource state. + enable_audit_agent (bool): + Whether to enable linux auditd logging on the workstation. + When enabled, a service account must also be specified that + has logging.buckets.write permission on the project. + Operating system audit logging is distinct from `Cloud Audit + Logs `__. + """ + + class Host(proto.Message): + r"""Runtime host for a workstation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gce_instance (google.cloud.workstations_v1beta.types.WorkstationConfig.Host.GceInstance): + Specifies a Compute Engine instance as the + host. + + This field is a member of `oneof`_ ``config``. + """ + + class GceInstance(proto.Message): + r"""A runtime using a Compute Engine instance. + + Attributes: + machine_type (str): + The name of a Compute Engine machine type. + service_account (str): + Email address of the service account used on + VM instances used to support this configuration. + If not set, VMs run with a Google-managed + service account. This service account must have + permission to pull the specified container + image; otherwise, the image must be publicly + accessible. + tags (MutableSequence[str]): + Network tags to add to the Compute Engine + machines backing the Workstations. + pool_size (int): + Number of instances to pool for faster + workstation startup. + pooled_instances (int): + Output only. Number of instances currently + available in the pool for faster workstation + startup. + disable_public_ip_addresses (bool): + Whether instances have no public IP address. + shielded_instance_config (google.cloud.workstations_v1beta.types.WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig): + A set of Compute Engine Shielded instance + options. + confidential_instance_config (google.cloud.workstations_v1beta.types.WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig): + A set of Compute Engine Confidential VM + instance options. + boot_disk_size_gb (int): + Size of the boot disk in GB. Defaults to 50. + accelerators (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig.Host.GceInstance.Accelerator]): + A list of the type and count of accelerator + cards attached to the instance. + """ + + class GceShieldedInstanceConfig(proto.Message): + r"""A set of Compute Engine Shielded instance options. + + Attributes: + enable_secure_boot (bool): + Whether the instance has Secure Boot enabled. + enable_vtpm (bool): + Whether the instance has the vTPM enabled. + enable_integrity_monitoring (bool): + Whether the instance has integrity monitoring + enabled. + """ + + enable_secure_boot: bool = proto.Field( + proto.BOOL, + number=1, + ) + enable_vtpm: bool = proto.Field( + proto.BOOL, + number=2, + ) + enable_integrity_monitoring: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class GceConfidentialInstanceConfig(proto.Message): + r"""A set of Compute Engine Confidential VM instance options. + + Attributes: + enable_confidential_compute (bool): + Whether the instance has confidential compute + enabled. + """ + + enable_confidential_compute: bool = proto.Field( + proto.BOOL, + number=1, + ) + + class Accelerator(proto.Message): + r"""An accelerator card attached to the instance. + + Attributes: + type_ (str): + Type of accelerator resource to attach to the + instance, for example, "nvidia-tesla-p100". + count (int): + Number of accelerator cards exposed to the + instance. + """ + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + count: int = proto.Field( + proto.INT32, + number=2, + ) + + machine_type: str = proto.Field( + proto.STRING, + number=1, + ) + service_account: str = proto.Field( + proto.STRING, + number=2, + ) + tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + pool_size: int = proto.Field( + proto.INT32, + number=5, + ) + pooled_instances: int = proto.Field( + proto.INT32, + number=12, + ) + disable_public_ip_addresses: bool = proto.Field( + proto.BOOL, + number=6, + ) + shielded_instance_config: 'WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig' = proto.Field( + proto.MESSAGE, + number=8, + message='WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig', + ) + confidential_instance_config: 'WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig' = proto.Field( + proto.MESSAGE, + number=10, + message='WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig', + ) + boot_disk_size_gb: int = proto.Field( + proto.INT32, + number=9, + ) + accelerators: MutableSequence['WorkstationConfig.Host.GceInstance.Accelerator'] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message='WorkstationConfig.Host.GceInstance.Accelerator', + ) + + gce_instance: 'WorkstationConfig.Host.GceInstance' = proto.Field( + proto.MESSAGE, + number=1, + oneof='config', + message='WorkstationConfig.Host.GceInstance', + ) + + class PersistentDirectory(proto.Message): + r"""A directory to persist across workstation sessions. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + mount_path (str): + Location of this directory in the running + workstation. + gce_pd (google.cloud.workstations_v1beta.types.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk): + A PersistentDirectory backed by a Compute + Engine persistent disk. + + This field is a member of `oneof`_ ``directory_type``. + """ + + class GceRegionalPersistentDisk(proto.Message): + r"""A PersistentDirectory backed by a Compute Engine regional + persistent disk. + + Attributes: + size_gb (int): + Size of the disk in GB. Must be empty if source_snapshot is + set. Defaults to 200. + fs_type (str): + Type of file system that the disk should be formatted with. + The workstation image must support this file system type. + Must be empty if source_snapshot is set. Defaults to ext4. + disk_type (str): + Type of the disk to use. Defaults to + pd-standard. + source_snapshot (str): + Name of the snapshot to use as the source for the disk. If + set, size_gb and fs_type must be empty. + reclaim_policy (google.cloud.workstations_v1beta.types.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy): + What should happen to the disk after the + workstation is deleted. Defaults to DELETE. + """ + class ReclaimPolicy(proto.Enum): + r"""Value representing what should happen to the disk after the + workstation is deleted. + + Values: + RECLAIM_POLICY_UNSPECIFIED (0): + Do not use. + DELETE (1): + The persistent disk will be deleted with the + workstation. + RETAIN (2): + The persistent disk will be remain after the + workstation is deleted, and the administrator + must manually delete the disk. + """ + RECLAIM_POLICY_UNSPECIFIED = 0 + DELETE = 1 + RETAIN = 2 + + size_gb: int = proto.Field( + proto.INT32, + number=1, + ) + fs_type: str = proto.Field( + proto.STRING, + number=2, + ) + disk_type: str = proto.Field( + proto.STRING, + number=3, + ) + source_snapshot: str = proto.Field( + proto.STRING, + number=5, + ) + reclaim_policy: 'WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy' = proto.Field( + proto.ENUM, + number=4, + enum='WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy', + ) + + mount_path: str = proto.Field( + proto.STRING, + number=1, + ) + gce_pd: 'WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk' = proto.Field( + proto.MESSAGE, + number=2, + oneof='directory_type', + message='WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk', + ) + + class Container(proto.Message): + r"""A Docker container. + + Attributes: + image (str): + Docker image defining the container. This + image must be accessible by the service account + specified in the workstation configuration. + command (MutableSequence[str]): + If set, overrides the default ENTRYPOINT + specified by the image. + args (MutableSequence[str]): + Arguments passed to the entrypoint. + env (MutableMapping[str, str]): + Environment variables passed to the + container's entrypoint. + working_dir (str): + If set, overrides the default DIR specified + by the image. + run_as_user (int): + If set, overrides the USER specified in the + image with the given uid. + """ + + image: str = proto.Field( + proto.STRING, + number=1, + ) + command: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + args: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + env: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + working_dir: str = proto.Field( + proto.STRING, + number=5, + ) + run_as_user: int = proto.Field( + proto.INT32, + number=6, + ) + + class CustomerEncryptionKey(proto.Message): + r"""A customer-managed encryption key for the Compute Engine + resources of this workstation configuration. + + Attributes: + kms_key (str): + Immutable. The name of the Google Cloud KMS encryption key. + For example, + ``projects/PROJECT_ID/locations/REGION/keyRings/KEY_RING/cryptoKeys/KEY_NAME``. + kms_key_service_account (str): + Immutable. The service account to use with the specified KMS + key. We recommend that you use a separate service account + and follow KMS best practices. For more information, see + `Separation of + duties `__ + and ``gcloud kms keys add-iam-policy-binding`` + ```--member`` `__. + """ + + kms_key: str = proto.Field( + proto.STRING, + number=1, + ) + kms_key_service_account: str = proto.Field( + proto.STRING, + number=2, + ) + + class ReadinessCheck(proto.Message): + r"""A readiness check to be performed on a workstation. + + Attributes: + path (str): + Path to which the request should be sent. + port (int): + Port to which the request should be sent. + """ + + path: str = proto.Field( + proto.STRING, + number=1, + ) + port: int = proto.Field( + proto.INT32, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=18, + ) + 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, + ) + idle_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=10, + message=duration_pb2.Duration, + ) + running_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=11, + message=duration_pb2.Duration, + ) + host: Host = proto.Field( + proto.MESSAGE, + number=12, + message=Host, + ) + persistent_directories: MutableSequence[PersistentDirectory] = proto.RepeatedField( + proto.MESSAGE, + number=13, + message=PersistentDirectory, + ) + container: Container = proto.Field( + proto.MESSAGE, + number=14, + message=Container, + ) + encryption_key: CustomerEncryptionKey = proto.Field( + proto.MESSAGE, + number=17, + message=CustomerEncryptionKey, + ) + readiness_checks: MutableSequence[ReadinessCheck] = proto.RepeatedField( + proto.MESSAGE, + number=19, + message=ReadinessCheck, + ) + degraded: bool = proto.Field( + proto.BOOL, + number=15, + ) + conditions: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=16, + message=status_pb2.Status, + ) + enable_audit_agent: bool = proto.Field( + proto.BOOL, + number=20, + ) + + +class Workstation(proto.Message): + r"""A single instance of a developer workstation with its own + persistent storage. + + Attributes: + name (str): + Full name of this resource. + display_name (str): + Human-readable name for this resource. + uid (str): + Output only. A system-assigned unique + identified for this resource. + reconciling (bool): + Output only. Indicates whether this resource + is currently being updated to match its intended + state. + annotations (MutableMapping[str, str]): + Client-specified annotations. + labels (MutableMapping[str, str]): + Client-specified labels that are applied to + the resource and that are also propagated to the + underlying Compute Engine resources. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this resource was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this resource was most + recently updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this resource was + soft-deleted. + etag (str): + Checksum computed by the server. May be sent + on update and delete requests to make sure that + the client has an up-to-date value before + proceeding. + state (google.cloud.workstations_v1beta.types.Workstation.State): + Output only. Current state of the + workstation. + host (str): + Output only. Host to which clients can send HTTPS traffic + that will be received by the workstation. Authorized traffic + will be received to the workstation as HTTP on port 80. To + send traffic to a different port, clients may prefix the + host with the destination port in the format + ``{port}-{host}``. + env (MutableMapping[str, str]): + Environment variables passed to the + workstation container's entrypoint. + """ + class State(proto.Enum): + r"""Whether a workstation is running and ready to receive user + requests. + + Values: + STATE_UNSPECIFIED (0): + Do not use. + STATE_STARTING (1): + The workstation is not yet ready to accept + requests from users but will be soon. + STATE_RUNNING (2): + The workstation is ready to accept requests + from users. + STATE_STOPPING (3): + The workstation is being stopped. + STATE_STOPPED (4): + The workstation is stopped and will not be + able to receive requests until it is started. + """ + STATE_UNSPECIFIED = 0 + STATE_STARTING = 1 + STATE_RUNNING = 2 + STATE_STOPPING = 3 + STATE_STOPPED = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + uid: str = proto.Field( + proto.STRING, + number=3, + ) + reconciling: bool = proto.Field( + proto.BOOL, + number=4, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=13, + ) + 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, + ) + state: State = proto.Field( + proto.ENUM, + number=10, + enum=State, + ) + host: str = proto.Field( + proto.STRING, + number=11, + ) + env: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=12, + ) + + +class GetWorkstationClusterRequest(proto.Message): + r"""Request message for GetWorkstationCluster. + + Attributes: + name (str): + Required. Name of the requested resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListWorkstationClustersRequest(proto.Message): + r"""Request message for ListWorkstationClusters. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Maximum number of items to return. + page_token (str): + next_page_token value returned from a previous List request, + if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListWorkstationClustersResponse(proto.Message): + r"""Response message for ListWorkstationClusters. + + Attributes: + workstation_clusters (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationCluster]): + The requested workstation clusters. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstation_clusters: MutableSequence['WorkstationCluster'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='WorkstationCluster', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateWorkstationClusterRequest(proto.Message): + r"""Message for creating a CreateWorkstationCluster. + + Attributes: + parent (str): + Required. Parent resource name. + workstation_cluster_id (str): + Required. ID to use for the workstation + cluster. + workstation_cluster (google.cloud.workstations_v1beta.types.WorkstationCluster): + Required. Workstation cluster to create. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + workstation_cluster_id: str = proto.Field( + proto.STRING, + number=2, + ) + workstation_cluster: 'WorkstationCluster' = proto.Field( + proto.MESSAGE, + number=3, + message='WorkstationCluster', + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateWorkstationClusterRequest(proto.Message): + r"""Request message for UpdateWorkstationCluster. + + Attributes: + workstation_cluster (google.cloud.workstations_v1beta.types.WorkstationCluster): + Required. Workstation cluster to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask that specifies which fields in + the workstation cluster should be updated. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + allow_missing (bool): + If set, and the workstation cluster is not found, a new + workstation cluster will be created. In this situation, + update_mask is ignored. + """ + + workstation_cluster: 'WorkstationCluster' = proto.Field( + proto.MESSAGE, + number=1, + message='WorkstationCluster', + ) + 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, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteWorkstationClusterRequest(proto.Message): + r"""Message for deleting a workstation cluster. + + Attributes: + name (str): + Required. Name of the workstation cluster to + delete. + validate_only (bool): + If set, validate the request and preview the + review, but do not apply it. + etag (str): + If set, the request will be rejected if the + latest version of the workstation cluster on the + server does not have this ETag. + force (bool): + If set, any workstation configurations and + workstations in the workstation cluster are also + deleted. Otherwise, the request only works if + the workstation cluster has no configurations or + workstations. + """ + + 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, + ) + force: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetWorkstationConfigRequest(proto.Message): + r"""Request message for GetWorkstationConfig. + + Attributes: + name (str): + Required. Name of the requested resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListWorkstationConfigsRequest(proto.Message): + r"""Request message for ListWorkstationConfigs. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Maximum number of items to return. + page_token (str): + next_page_token value returned from a previous List request, + if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListWorkstationConfigsResponse(proto.Message): + r"""Response message for ListWorkstationConfigs. + + Attributes: + workstation_configs (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig]): + The requested configs. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstation_configs: MutableSequence['WorkstationConfig'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='WorkstationConfig', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ListUsableWorkstationConfigsRequest(proto.Message): + r"""Request message for ListUsableWorkstationConfigs. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Maximum number of items to return. + page_token (str): + next_page_token value returned from a previous List request, + if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListUsableWorkstationConfigsResponse(proto.Message): + r"""Response message for ListUsableWorkstationConfigs. + + Attributes: + workstation_configs (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig]): + The requested configs. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstation_configs: MutableSequence['WorkstationConfig'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='WorkstationConfig', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateWorkstationConfigRequest(proto.Message): + r"""Message for creating a CreateWorkstationConfig. + + Attributes: + parent (str): + Required. Parent resource name. + workstation_config_id (str): + Required. ID to use for the workstation + configuration. + workstation_config (google.cloud.workstations_v1beta.types.WorkstationConfig): + Required. Config to create. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + workstation_config_id: str = proto.Field( + proto.STRING, + number=2, + ) + workstation_config: 'WorkstationConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='WorkstationConfig', + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateWorkstationConfigRequest(proto.Message): + r"""Request message for UpdateWorkstationConfig. + + Attributes: + workstation_config (google.cloud.workstations_v1beta.types.WorkstationConfig): + Required. Config to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask specifying which fields in the + workstation configuration should be updated. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + allow_missing (bool): + If set and the workstation configuration is not found, a new + workstation configuration will be created. In this + situation, update_mask is ignored. + """ + + workstation_config: 'WorkstationConfig' = proto.Field( + proto.MESSAGE, + number=1, + message='WorkstationConfig', + ) + 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, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteWorkstationConfigRequest(proto.Message): + r"""Message for deleting a workstation configuration. + + Attributes: + name (str): + Required. Name of the workstation + configuration to delete. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + etag (str): + If set, the request is rejected if the latest + version of the workstation configuration on the + server does not have this ETag. + force (bool): + If set, any workstations in the workstation + configuration are also deleted. Otherwise, the + request works only if the workstation + configuration has no workstations. + """ + + 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, + ) + force: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetWorkstationRequest(proto.Message): + r"""Request message for GetWorkstation. + + Attributes: + name (str): + Required. Name of the requested resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListWorkstationsRequest(proto.Message): + r"""Request message for ListWorkstations. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Maximum number of items to return. + page_token (str): + next_page_token value returned from a previous List request, + if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListWorkstationsResponse(proto.Message): + r"""Response message for ListWorkstations. + + Attributes: + workstations (MutableSequence[google.cloud.workstations_v1beta.types.Workstation]): + The requested workstations. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstations: MutableSequence['Workstation'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Workstation', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ListUsableWorkstationsRequest(proto.Message): + r"""Request message for ListUsableWorkstations. + + Attributes: + parent (str): + Required. Parent resource name. + page_size (int): + Maximum number of items to return. + page_token (str): + next_page_token value returned from a previous List request, + if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListUsableWorkstationsResponse(proto.Message): + r"""Response message for ListUsableWorkstations. + + Attributes: + workstations (MutableSequence[google.cloud.workstations_v1beta.types.Workstation]): + The requested workstations. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Unreachable resources. + """ + + @property + def raw_page(self): + return self + + workstations: MutableSequence['Workstation'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Workstation', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateWorkstationRequest(proto.Message): + r"""Message for creating a CreateWorkstation. + + Attributes: + parent (str): + Required. Parent resource name. + workstation_id (str): + Required. ID to use for the workstation. + workstation (google.cloud.workstations_v1beta.types.Workstation): + Required. Workstation to create. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + workstation_id: str = proto.Field( + proto.STRING, + number=2, + ) + workstation: 'Workstation' = proto.Field( + proto.MESSAGE, + number=3, + message='Workstation', + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class UpdateWorkstationRequest(proto.Message): + r"""Request message for UpdateWorkstation. + + Attributes: + workstation (google.cloud.workstations_v1beta.types.Workstation): + Required. Workstation to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask specifying which fields in the + workstation configuration should be updated. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + allow_missing (bool): + If set and the workstation configuration is not found, a new + workstation configuration is created. In this situation, + update_mask is ignored. + """ + + workstation: 'Workstation' = proto.Field( + proto.MESSAGE, + number=1, + message='Workstation', + ) + 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, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteWorkstationRequest(proto.Message): + r"""Request message for DeleteWorkstation. + + Attributes: + name (str): + Required. Name of the workstation to delete. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + etag (str): + If set, the request will be rejected if the + latest version of the workstation on the server + does not have this ETag. + """ + + 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 StartWorkstationRequest(proto.Message): + r"""Request message for StartWorkstation. + + Attributes: + name (str): + Required. Name of the workstation to start. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + etag (str): + If set, the request will be rejected if the + latest version of the workstation on the server + does not have this ETag. + """ + + 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 StopWorkstationRequest(proto.Message): + r"""Request message for StopWorkstation. + + Attributes: + name (str): + Required. Name of the workstation to stop. + validate_only (bool): + If set, validate the request and preview the + review, but do not actually apply it. + etag (str): + If set, the request will be rejected if the + latest version of the workstation on the server + does not have this ETag. + """ + + 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 GenerateAccessTokenRequest(proto.Message): + r"""Request message for GenerateAccessToken. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + workstation (str): + Required. Name of the workstation for which + the access token should be generated. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Desired expiration time of the access token. + This value must be at most 24 hours in the + future. If a value is not specified, the token's + expiration time will be set to a default value + of 1 hour in the future. + + This field is a member of `oneof`_ ``expiration``. + ttl (google.protobuf.duration_pb2.Duration): + Desired lifetime duration of the access + token. This value must be at most 24 hours. If a + value is not specified, the token's lifetime + will be set to a default value of 1 hour. + + This field is a member of `oneof`_ ``expiration``. + """ + + workstation: str = proto.Field( + proto.STRING, + number=1, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + oneof='expiration', + message=timestamp_pb2.Timestamp, + ) + ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + oneof='expiration', + message=duration_pb2.Duration, + ) + + +class GenerateAccessTokenResponse(proto.Message): + r"""Response message for GenerateAccessToken. + + Attributes: + access_token (str): + The generated bearer access token. To use this token, + include it in an Authorization header of an HTTP request + sent to the associated workstation's hostname—for example, + ``Authorization: Bearer ``. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which the generated token will + expire. + """ + + access_token: str = proto.Field( + proto.STRING, + number=1, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class OperationMetadata(proto.Message): + r"""Metadata for long-running operations. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time that the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time that the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has + requested cancellation of the operation. + api_version (str): + Output only. API version used to start the + operation. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + status_message: str = proto.Field( + proto.STRING, + number=5, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/mypy.ini b/owl-bot-staging/google-cloud-workstations/v1beta/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/noxfile.py b/owl-bot-staging/google-cloud-workstations/v1beta/noxfile.py new file mode 100644 index 000000000000..3f0ab930ba46 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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/workstations_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json new file mode 100644 index 000000000000..8afcd1793b5c --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json @@ -0,0 +1,3307 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.workstations.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-cloud-workstations", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.create_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.CreateWorkstationClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation_cluster", + "type": "google.cloud.workstations_v1beta.types.WorkstationCluster" + }, + { + "name": "workstation_cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_workstation_cluster" + }, + "description": "Sample for CreateWorkstationCluster", + "file": "workstations_v1beta_generated_workstations_create_workstation_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstationCluster_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": "workstations_v1beta_generated_workstations_create_workstation_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.create_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.CreateWorkstationClusterRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation_cluster", + "type": "google.cloud.workstations_v1beta.types.WorkstationCluster" + }, + { + "name": "workstation_cluster_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_workstation_cluster" + }, + "description": "Sample for CreateWorkstationCluster", + "file": "workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstationCluster_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": "workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.create_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.CreateWorkstationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation_config", + "type": "google.cloud.workstations_v1beta.types.WorkstationConfig" + }, + { + "name": "workstation_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_workstation_config" + }, + "description": "Sample for CreateWorkstationConfig", + "file": "workstations_v1beta_generated_workstations_create_workstation_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstationConfig_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": "workstations_v1beta_generated_workstations_create_workstation_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.create_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.CreateWorkstationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation_config", + "type": "google.cloud.workstations_v1beta.types.WorkstationConfig" + }, + { + "name": "workstation_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_workstation_config" + }, + "description": "Sample for CreateWorkstationConfig", + "file": "workstations_v1beta_generated_workstations_create_workstation_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstationConfig_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": "workstations_v1beta_generated_workstations_create_workstation_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.create_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.CreateWorkstationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation", + "type": "google.cloud.workstations_v1beta.types.Workstation" + }, + { + "name": "workstation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_workstation" + }, + "description": "Sample for CreateWorkstation", + "file": "workstations_v1beta_generated_workstations_create_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstation_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": "workstations_v1beta_generated_workstations_create_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.create_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "CreateWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.CreateWorkstationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "workstation", + "type": "google.cloud.workstations_v1beta.types.Workstation" + }, + { + "name": "workstation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_workstation" + }, + "description": "Sample for CreateWorkstation", + "file": "workstations_v1beta_generated_workstations_create_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstation_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": "workstations_v1beta_generated_workstations_create_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.delete_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationClusterRequest" + }, + { + "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_workstation_cluster" + }, + "description": "Sample for DeleteWorkstationCluster", + "file": "workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_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": "workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.delete_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationClusterRequest" + }, + { + "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_workstation_cluster" + }, + "description": "Sample for DeleteWorkstationCluster", + "file": "workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_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": "workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.delete_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationConfigRequest" + }, + { + "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_workstation_config" + }, + "description": "Sample for DeleteWorkstationConfig", + "file": "workstations_v1beta_generated_workstations_delete_workstation_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_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": "workstations_v1beta_generated_workstations_delete_workstation_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.delete_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationConfigRequest" + }, + { + "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_workstation_config" + }, + "description": "Sample for DeleteWorkstationConfig", + "file": "workstations_v1beta_generated_workstations_delete_workstation_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_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": "workstations_v1beta_generated_workstations_delete_workstation_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.delete_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationRequest" + }, + { + "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_workstation" + }, + "description": "Sample for DeleteWorkstation", + "file": "workstations_v1beta_generated_workstations_delete_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstation_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": "workstations_v1beta_generated_workstations_delete_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.delete_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "DeleteWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationRequest" + }, + { + "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_workstation" + }, + "description": "Sample for DeleteWorkstation", + "file": "workstations_v1beta_generated_workstations_delete_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstation_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": "workstations_v1beta_generated_workstations_delete_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.generate_access_token", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.GenerateAccessToken", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "GenerateAccessToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.GenerateAccessTokenRequest" + }, + { + "name": "workstation", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.types.GenerateAccessTokenResponse", + "shortName": "generate_access_token" + }, + "description": "Sample for GenerateAccessToken", + "file": "workstations_v1beta_generated_workstations_generate_access_token_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_GenerateAccessToken_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": "workstations_v1beta_generated_workstations_generate_access_token_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.generate_access_token", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.GenerateAccessToken", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "GenerateAccessToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.GenerateAccessTokenRequest" + }, + { + "name": "workstation", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.workstations_v1beta.types.GenerateAccessTokenResponse", + "shortName": "generate_access_token" + }, + "description": "Sample for GenerateAccessToken", + "file": "workstations_v1beta_generated_workstations_generate_access_token_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_GenerateAccessToken_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": "workstations_v1beta_generated_workstations_generate_access_token_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.get_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.GetWorkstationClusterRequest" + }, + { + "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.workstations_v1beta.types.WorkstationCluster", + "shortName": "get_workstation_cluster" + }, + "description": "Sample for GetWorkstationCluster", + "file": "workstations_v1beta_generated_workstations_get_workstation_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstationCluster_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": "workstations_v1beta_generated_workstations_get_workstation_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.get_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.GetWorkstationClusterRequest" + }, + { + "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.workstations_v1beta.types.WorkstationCluster", + "shortName": "get_workstation_cluster" + }, + "description": "Sample for GetWorkstationCluster", + "file": "workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstationCluster_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": "workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.get_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.GetWorkstationConfigRequest" + }, + { + "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.workstations_v1beta.types.WorkstationConfig", + "shortName": "get_workstation_config" + }, + "description": "Sample for GetWorkstationConfig", + "file": "workstations_v1beta_generated_workstations_get_workstation_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstationConfig_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": "workstations_v1beta_generated_workstations_get_workstation_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.get_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.GetWorkstationConfigRequest" + }, + { + "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.workstations_v1beta.types.WorkstationConfig", + "shortName": "get_workstation_config" + }, + "description": "Sample for GetWorkstationConfig", + "file": "workstations_v1beta_generated_workstations_get_workstation_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstationConfig_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": "workstations_v1beta_generated_workstations_get_workstation_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.get_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.GetWorkstationRequest" + }, + { + "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.workstations_v1beta.types.Workstation", + "shortName": "get_workstation" + }, + "description": "Sample for GetWorkstation", + "file": "workstations_v1beta_generated_workstations_get_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstation_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": "workstations_v1beta_generated_workstations_get_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.get_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "GetWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.GetWorkstationRequest" + }, + { + "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.workstations_v1beta.types.Workstation", + "shortName": "get_workstation" + }, + "description": "Sample for GetWorkstation", + "file": "workstations_v1beta_generated_workstations_get_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstation_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": "workstations_v1beta_generated_workstations_get_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_usable_workstation_configs", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListUsableWorkstationConfigs", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListUsableWorkstationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest" + }, + { + "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.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationConfigsAsyncPager", + "shortName": "list_usable_workstation_configs" + }, + "description": "Sample for ListUsableWorkstationConfigs", + "file": "workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_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": "workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_usable_workstation_configs", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListUsableWorkstationConfigs", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListUsableWorkstationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest" + }, + { + "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.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationConfigsPager", + "shortName": "list_usable_workstation_configs" + }, + "description": "Sample for ListUsableWorkstationConfigs", + "file": "workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_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": "workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_usable_workstations", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListUsableWorkstations", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListUsableWorkstations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest" + }, + { + "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.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationsAsyncPager", + "shortName": "list_usable_workstations" + }, + "description": "Sample for ListUsableWorkstations", + "file": "workstations_v1beta_generated_workstations_list_usable_workstations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListUsableWorkstations_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": "workstations_v1beta_generated_workstations_list_usable_workstations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_usable_workstations", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListUsableWorkstations", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListUsableWorkstations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest" + }, + { + "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.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationsPager", + "shortName": "list_usable_workstations" + }, + "description": "Sample for ListUsableWorkstations", + "file": "workstations_v1beta_generated_workstations_list_usable_workstations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListUsableWorkstations_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": "workstations_v1beta_generated_workstations_list_usable_workstations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_workstation_clusters", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstationClusters", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstationClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest" + }, + { + "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.workstations_v1beta.services.workstations.pagers.ListWorkstationClustersAsyncPager", + "shortName": "list_workstation_clusters" + }, + "description": "Sample for ListWorkstationClusters", + "file": "workstations_v1beta_generated_workstations_list_workstation_clusters_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstationClusters_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": "workstations_v1beta_generated_workstations_list_workstation_clusters_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_workstation_clusters", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstationClusters", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstationClusters" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest" + }, + { + "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.workstations_v1beta.services.workstations.pagers.ListWorkstationClustersPager", + "shortName": "list_workstation_clusters" + }, + "description": "Sample for ListWorkstationClusters", + "file": "workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstationClusters_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": "workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_workstation_configs", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstationConfigs", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest" + }, + { + "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.workstations_v1beta.services.workstations.pagers.ListWorkstationConfigsAsyncPager", + "shortName": "list_workstation_configs" + }, + "description": "Sample for ListWorkstationConfigs", + "file": "workstations_v1beta_generated_workstations_list_workstation_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstationConfigs_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": "workstations_v1beta_generated_workstations_list_workstation_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_workstation_configs", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstationConfigs", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest" + }, + { + "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.workstations_v1beta.services.workstations.pagers.ListWorkstationConfigsPager", + "shortName": "list_workstation_configs" + }, + "description": "Sample for ListWorkstationConfigs", + "file": "workstations_v1beta_generated_workstations_list_workstation_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstationConfigs_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": "workstations_v1beta_generated_workstations_list_workstation_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_workstations", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstations", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListWorkstationsRequest" + }, + { + "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.workstations_v1beta.services.workstations.pagers.ListWorkstationsAsyncPager", + "shortName": "list_workstations" + }, + "description": "Sample for ListWorkstations", + "file": "workstations_v1beta_generated_workstations_list_workstations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstations_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": "workstations_v1beta_generated_workstations_list_workstations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_workstations", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstations", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "ListWorkstations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.ListWorkstationsRequest" + }, + { + "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.workstations_v1beta.services.workstations.pagers.ListWorkstationsPager", + "shortName": "list_workstations" + }, + "description": "Sample for ListWorkstations", + "file": "workstations_v1beta_generated_workstations_list_workstations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstations_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": "workstations_v1beta_generated_workstations_list_workstations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.start_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.StartWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "StartWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.StartWorkstationRequest" + }, + { + "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": "start_workstation" + }, + "description": "Sample for StartWorkstation", + "file": "workstations_v1beta_generated_workstations_start_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_StartWorkstation_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": "workstations_v1beta_generated_workstations_start_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.start_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.StartWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "StartWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.StartWorkstationRequest" + }, + { + "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": "start_workstation" + }, + "description": "Sample for StartWorkstation", + "file": "workstations_v1beta_generated_workstations_start_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_StartWorkstation_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": "workstations_v1beta_generated_workstations_start_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.stop_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.StopWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "StopWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.StopWorkstationRequest" + }, + { + "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": "stop_workstation" + }, + "description": "Sample for StopWorkstation", + "file": "workstations_v1beta_generated_workstations_stop_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_StopWorkstation_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": "workstations_v1beta_generated_workstations_stop_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.stop_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.StopWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "StopWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.StopWorkstationRequest" + }, + { + "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": "stop_workstation" + }, + "description": "Sample for StopWorkstation", + "file": "workstations_v1beta_generated_workstations_stop_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_StopWorkstation_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": "workstations_v1beta_generated_workstations_stop_workstation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.update_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationClusterRequest" + }, + { + "name": "workstation_cluster", + "type": "google.cloud.workstations_v1beta.types.WorkstationCluster" + }, + { + "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_workstation_cluster" + }, + "description": "Sample for UpdateWorkstationCluster", + "file": "workstations_v1beta_generated_workstations_update_workstation_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_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": "workstations_v1beta_generated_workstations_update_workstation_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.update_workstation_cluster", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstationCluster", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstationCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationClusterRequest" + }, + { + "name": "workstation_cluster", + "type": "google.cloud.workstations_v1beta.types.WorkstationCluster" + }, + { + "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_workstation_cluster" + }, + "description": "Sample for UpdateWorkstationCluster", + "file": "workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_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": "workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.update_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationConfigRequest" + }, + { + "name": "workstation_config", + "type": "google.cloud.workstations_v1beta.types.WorkstationConfig" + }, + { + "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_workstation_config" + }, + "description": "Sample for UpdateWorkstationConfig", + "file": "workstations_v1beta_generated_workstations_update_workstation_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_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": "workstations_v1beta_generated_workstations_update_workstation_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.update_workstation_config", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstationConfig", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationConfigRequest" + }, + { + "name": "workstation_config", + "type": "google.cloud.workstations_v1beta.types.WorkstationConfig" + }, + { + "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_workstation_config" + }, + "description": "Sample for UpdateWorkstationConfig", + "file": "workstations_v1beta_generated_workstations_update_workstation_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_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": "workstations_v1beta_generated_workstations_update_workstation_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", + "shortName": "WorkstationsAsyncClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.update_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationRequest" + }, + { + "name": "workstation", + "type": "google.cloud.workstations_v1beta.types.Workstation" + }, + { + "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_workstation" + }, + "description": "Sample for UpdateWorkstation", + "file": "workstations_v1beta_generated_workstations_update_workstation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstation_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": "workstations_v1beta_generated_workstations_update_workstation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", + "shortName": "WorkstationsClient" + }, + "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.update_workstation", + "method": { + "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstation", + "service": { + "fullName": "google.cloud.workstations.v1beta.Workstations", + "shortName": "Workstations" + }, + "shortName": "UpdateWorkstation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationRequest" + }, + { + "name": "workstation", + "type": "google.cloud.workstations_v1beta.types.Workstation" + }, + { + "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_workstation" + }, + "description": "Sample for UpdateWorkstation", + "file": "workstations_v1beta_generated_workstations_update_workstation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstation_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": "workstations_v1beta_generated_workstations_update_workstation_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_async.py new file mode 100644 index 000000000000..be67b4246ac4 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_CreateWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_create_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationRequest( + parent="parent_value", + workstation_id="workstation_id_value", + ) + + # Make the request + operation = client.create_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_CreateWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_async.py new file mode 100644 index 000000000000..9b136279f21a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_CreateWorkstationCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_create_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationClusterRequest( + parent="parent_value", + workstation_cluster_id="workstation_cluster_id_value", + ) + + # Make the request + operation = client.create_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_CreateWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py new file mode 100644 index 000000000000..fcf1bcea66d1 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_CreateWorkstationCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_create_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationClusterRequest( + parent="parent_value", + workstation_cluster_id="workstation_cluster_id_value", + ) + + # Make the request + operation = client.create_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_CreateWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_async.py new file mode 100644 index 000000000000..7be0818eccb4 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_CreateWorkstationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_create_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationConfigRequest( + parent="parent_value", + workstation_config_id="workstation_config_id_value", + ) + + # Make the request + operation = client.create_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_CreateWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_sync.py new file mode 100644 index 000000000000..bdf2496d486c --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_CreateWorkstationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_create_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationConfigRequest( + parent="parent_value", + workstation_config_id="workstation_config_id_value", + ) + + # Make the request + operation = client.create_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_CreateWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_sync.py new file mode 100644 index 000000000000..b841bfbb8d8d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_CreateWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_create_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.CreateWorkstationRequest( + parent="parent_value", + workstation_id="workstation_id_value", + ) + + # Make the request + operation = client.create_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_CreateWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_async.py new file mode 100644 index 000000000000..6f544d0f9324 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_DeleteWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_delete_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_DeleteWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py new file mode 100644 index 000000000000..4ca8290db920 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_delete_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py new file mode 100644 index 000000000000..d8b839644d89 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_delete_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_async.py new file mode 100644 index 000000000000..6124931d5494 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_delete_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_sync.py new file mode 100644 index 000000000000..1fa571dd19ca --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_delete_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_sync.py new file mode 100644 index 000000000000..c472ff766271 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_DeleteWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_delete_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.DeleteWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_DeleteWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_async.py new file mode 100644 index 000000000000..c48ea1e2bafd --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateAccessToken +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_GenerateAccessToken_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_generate_access_token(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.GenerateAccessTokenRequest( + workstation="workstation_value", + ) + + # Make the request + response = await client.generate_access_token(request=request) + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_GenerateAccessToken_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_sync.py new file mode 100644 index 000000000000..263cb465e60a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateAccessToken +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_GenerateAccessToken_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_generate_access_token(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.GenerateAccessTokenRequest( + workstation="workstation_value", + ) + + # Make the request + response = client.generate_access_token(request=request) + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_GenerateAccessToken_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_async.py new file mode 100644 index 000000000000..06b3380ee695 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_GetWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_get_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation(request=request) + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_GetWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_async.py new file mode 100644 index 000000000000..33706220659e --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_GetWorkstationCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_get_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation_cluster(request=request) + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_GetWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py new file mode 100644 index 000000000000..0eaa770a84e4 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_GetWorkstationCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_get_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationClusterRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation_cluster(request=request) + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_GetWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_async.py new file mode 100644 index 000000000000..3826622fc27d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_GetWorkstationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_get_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workstation_config(request=request) + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_GetWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_sync.py new file mode 100644 index 000000000000..3b2378263be8 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_GetWorkstationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_get_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation_config(request=request) + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_GetWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_sync.py new file mode 100644 index 000000000000..8f2387aa7d5a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_GetWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_get_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.GetWorkstationRequest( + name="name_value", + ) + + # Make the request + response = client.get_workstation(request=request) + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_GetWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py new file mode 100644 index 000000000000..85349489cc32 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUsableWorkstationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_list_usable_workstation_configs(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListUsableWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstation_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py new file mode 100644 index 000000000000..1d5253a514e9 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUsableWorkstationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_list_usable_workstation_configs(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListUsableWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstation_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_async.py new file mode 100644 index 000000000000..c3a757c5ca1d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUsableWorkstations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListUsableWorkstations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_list_usable_workstations(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListUsableWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListUsableWorkstations_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_sync.py new file mode 100644 index 000000000000..d93a51c1ae18 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUsableWorkstations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListUsableWorkstations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_list_usable_workstations(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListUsableWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_usable_workstations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListUsableWorkstations_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_async.py new file mode 100644 index 000000000000..99c25e91565c --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListWorkstationClusters +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListWorkstationClusters_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_list_workstation_clusters(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_clusters(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListWorkstationClusters_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py new file mode 100644 index 000000000000..977a14ef9606 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListWorkstationClusters +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListWorkstationClusters_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_list_workstation_clusters(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationClustersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_clusters(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListWorkstationClusters_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_async.py new file mode 100644 index 000000000000..6cf8fd8e387d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListWorkstationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListWorkstationConfigs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_list_workstation_configs(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListWorkstationConfigs_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_sync.py new file mode 100644 index 000000000000..3a2b40396cde --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListWorkstationConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListWorkstationConfigs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_list_workstation_configs(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstation_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListWorkstationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_async.py new file mode 100644 index 000000000000..344f96f8712e --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListWorkstations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListWorkstations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_list_workstations(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListWorkstations_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_sync.py new file mode 100644 index 000000000000..94220467c51d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListWorkstations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_ListWorkstations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_list_workstations(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.ListWorkstationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workstations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END workstations_v1beta_generated_Workstations_ListWorkstations_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_async.py new file mode 100644 index 000000000000..8b2a6fae61a3 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StartWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_StartWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_start_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.StartWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.start_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_StartWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_sync.py new file mode 100644 index 000000000000..2cc02373acf6 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StartWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_StartWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_start_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.StartWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.start_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_StartWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_async.py new file mode 100644 index 000000000000..34af46912505 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StopWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_StopWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_stop_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.StopWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_StopWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_sync.py new file mode 100644 index 000000000000..023274feb4e4 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StopWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_StopWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_stop_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.StopWorkstationRequest( + name="name_value", + ) + + # Make the request + operation = client.stop_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_StopWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_async.py new file mode 100644 index 000000000000..7c475a71fae9 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_UpdateWorkstation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_update_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationRequest( + ) + + # Make the request + operation = client.update_workstation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_UpdateWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_async.py new file mode 100644 index 000000000000..89b200ae4115 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_update_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationClusterRequest( + ) + + # Make the request + operation = client.update_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py new file mode 100644 index 000000000000..2f431bd63d3f --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateWorkstationCluster +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_update_workstation_cluster(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationClusterRequest( + ) + + # Make the request + operation = client.update_workstation_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_async.py new file mode 100644 index 000000000000..2ca5c4c80b0a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +async def sample_update_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsAsyncClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationConfigRequest( + ) + + # Make the request + operation = client.update_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_sync.py new file mode 100644 index 000000000000..c6080dd0951c --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateWorkstationConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_update_workstation_config(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationConfigRequest( + ) + + # Make the request + operation = client.update_workstation_config(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_sync.py new file mode 100644 index 000000000000..450b03b0fb44 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateWorkstation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-workstations + + +# [START workstations_v1beta_generated_Workstations_UpdateWorkstation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import workstations_v1beta + + +def sample_update_workstation(): + # Create a client + client = workstations_v1beta.WorkstationsClient() + + # Initialize request argument(s) + request = workstations_v1beta.UpdateWorkstationRequest( + ) + + # Make the request + operation = client.update_workstation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END workstations_v1beta_generated_Workstations_UpdateWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/scripts/fixup_workstations_v1beta_keywords.py b/owl-bot-staging/google-cloud-workstations/v1beta/scripts/fixup_workstations_v1beta_keywords.py new file mode 100644 index 000000000000..4f7ba7cb1e17 --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/scripts/fixup_workstations_v1beta_keywords.py @@ -0,0 +1,195 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 workstationsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_workstation': ('parent', 'workstation_id', 'workstation', 'validate_only', ), + 'create_workstation_cluster': ('parent', 'workstation_cluster_id', 'workstation_cluster', 'validate_only', ), + 'create_workstation_config': ('parent', 'workstation_config_id', 'workstation_config', 'validate_only', ), + 'delete_workstation': ('name', 'validate_only', 'etag', ), + 'delete_workstation_cluster': ('name', 'validate_only', 'etag', 'force', ), + 'delete_workstation_config': ('name', 'validate_only', 'etag', 'force', ), + 'generate_access_token': ('workstation', 'expire_time', 'ttl', ), + 'get_workstation': ('name', ), + 'get_workstation_cluster': ('name', ), + 'get_workstation_config': ('name', ), + 'list_usable_workstation_configs': ('parent', 'page_size', 'page_token', ), + 'list_usable_workstations': ('parent', 'page_size', 'page_token', ), + 'list_workstation_clusters': ('parent', 'page_size', 'page_token', ), + 'list_workstation_configs': ('parent', 'page_size', 'page_token', ), + 'list_workstations': ('parent', 'page_size', 'page_token', ), + 'start_workstation': ('name', 'validate_only', 'etag', ), + 'stop_workstation': ('name', 'validate_only', 'etag', ), + 'update_workstation': ('workstation', 'update_mask', 'validate_only', 'allow_missing', ), + 'update_workstation_cluster': ('workstation_cluster', 'update_mask', 'validate_only', 'allow_missing', ), + 'update_workstation_config': ('workstation_config', 'update_mask', 'validate_only', 'allow_missing', ), + } + + 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=workstationsCallTransformer(), +): + """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 workstations client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/setup.py b/owl-bot-staging/google-cloud-workstations/v1beta/setup.py new file mode 100644 index 000000000000..1483952d60ff --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/setup.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-workstations' + + +description = "Google Cloud Workstations API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/workstations/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-workstations" + +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/google-cloud-workstations/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.7.txt new file mode 100644 index 000000000000..2beecf99e0be --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/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/google-cloud-workstations/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/tests/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/test_workstations.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/test_workstations.py new file mode 100644 index 000000000000..a60ab176597a --- /dev/null +++ b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/test_workstations.py @@ -0,0 +1,13504 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.location import locations_pb2 +from google.cloud.workstations_v1beta.services.workstations import WorkstationsAsyncClient +from google.cloud.workstations_v1beta.services.workstations import WorkstationsClient +from google.cloud.workstations_v1beta.services.workstations import pagers +from google.cloud.workstations_v1beta.services.workstations import transports +from google.cloud.workstations_v1beta.types import workstations +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 any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_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 WorkstationsClient._get_default_mtls_endpoint(None) is None + assert WorkstationsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert WorkstationsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert WorkstationsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert WorkstationsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert WorkstationsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (WorkstationsClient, "grpc"), + (WorkstationsAsyncClient, "grpc_asyncio"), + (WorkstationsClient, "rest"), +]) +def test_workstations_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 == ( + 'workstations.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://workstations.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.WorkstationsGrpcTransport, "grpc"), + (transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.WorkstationsRestTransport, "rest"), +]) +def test_workstations_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", [ + (WorkstationsClient, "grpc"), + (WorkstationsAsyncClient, "grpc_asyncio"), + (WorkstationsClient, "rest"), +]) +def test_workstations_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 == ( + 'workstations.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://workstations.googleapis.com' + ) + + +def test_workstations_client_get_transport_class(): + transport = WorkstationsClient.get_transport_class() + available_transports = [ + transports.WorkstationsGrpcTransport, + transports.WorkstationsRestTransport, + ] + assert transport in available_transports + + transport = WorkstationsClient.get_transport_class("grpc") + assert transport == transports.WorkstationsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), +]) +@mock.patch.object(WorkstationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsClient)) +@mock.patch.object(WorkstationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsAsyncClient)) +def test_workstations_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(WorkstationsClient, '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(WorkstationsClient, '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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", "true"), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", "false"), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest", "true"), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest", "false"), +]) +@mock.patch.object(WorkstationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsClient)) +@mock.patch.object(WorkstationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_workstations_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", [ + WorkstationsClient, WorkstationsAsyncClient +]) +@mock.patch.object(WorkstationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsClient)) +@mock.patch.object(WorkstationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsAsyncClient)) +def test_workstations_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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), +]) +def test_workstations_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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", grpc_helpers), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (WorkstationsClient, transports.WorkstationsRestTransport, "rest", None), +]) +def test_workstations_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_workstations_client_client_options_from_dict(): + with mock.patch('google.cloud.workstations_v1beta.services.workstations.transports.WorkstationsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = WorkstationsClient( + 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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", grpc_helpers), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_workstations_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( + "workstations.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="workstations.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationClusterRequest, + dict, +]) +def test_get_workstation_cluster(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationCluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + network='network_value', + subnetwork='subnetwork_value', + control_plane_ip='control_plane_ip_value', + degraded=True, + ) + response = client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationCluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.network == 'network_value' + assert response.subnetwork == 'subnetwork_value' + assert response.control_plane_ip == 'control_plane_ip_value' + assert response.degraded is True + + +def test_get_workstation_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_cluster), + '__call__') as call: + client.get_workstation_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationClusterRequest() + +@pytest.mark.asyncio +async def test_get_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationClusterRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + network='network_value', + subnetwork='subnetwork_value', + control_plane_ip='control_plane_ip_value', + degraded=True, + )) + response = await client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationCluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.network == 'network_value' + assert response.subnetwork == 'subnetwork_value' + assert response.control_plane_ip == 'control_plane_ip_value' + assert response.degraded is True + + +@pytest.mark.asyncio +async def test_get_workstation_cluster_async_from_dict(): + await test_get_workstation_cluster_async(request_type=dict) + + +def test_get_workstation_cluster_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + call.return_value = workstations.WorkstationCluster() + client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster()) + await client.get_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationCluster() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_workstation_cluster( + 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_workstation_cluster_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_cluster( + workstations.GetWorkstationClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_workstation_cluster_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationCluster() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_workstation_cluster( + 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_workstation_cluster_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_cluster( + workstations.GetWorkstationClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationClustersRequest, + dict, +]) +def test_list_workstation_clusters(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationClustersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationClustersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workstation_clusters_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_clusters), + '__call__') as call: + client.list_workstation_clusters() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationClustersRequest() + +@pytest.mark.asyncio +async def test_list_workstation_clusters_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationClustersRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationClustersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationClustersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_workstation_clusters_async_from_dict(): + await test_list_workstation_clusters_async(request_type=dict) + + +def test_list_workstation_clusters_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + call.return_value = workstations.ListWorkstationClustersResponse() + client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_workstation_clusters_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationClustersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse()) + await client.list_workstation_clusters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_workstation_clusters_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationClustersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_workstation_clusters( + 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_workstation_clusters_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_clusters( + workstations.ListWorkstationClustersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_workstation_clusters_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationClustersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_workstation_clusters( + 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_workstation_clusters_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_clusters( + workstations.ListWorkstationClustersRequest(), + parent='parent_value', + ) + + +def test_list_workstation_clusters_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstation_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_workstation_clusters(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.WorkstationCluster) + for i in results) +def test_list_workstation_clusters_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstation_clusters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + RuntimeError, + ) + pages = list(client.list_workstation_clusters(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_workstation_clusters_async_pager(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_workstation_clusters(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, workstations.WorkstationCluster) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_workstation_clusters_async_pages(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_clusters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_workstation_clusters(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + workstations.CreateWorkstationClusterRequest, + dict, +]) +def test_create_workstation_cluster(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_workstation_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_cluster), + '__call__') as call: + client.create_workstation_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationClusterRequest() + +@pytest.mark.asyncio +async def test_create_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationClusterRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__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_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_workstation_cluster_async_from_dict(): + await test_create_workstation_cluster_async(request_type=dict) + + +def test_create_workstation_cluster_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_workstation_cluster_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationClusterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_workstation_cluster_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__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_workstation_cluster( + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].workstation_cluster + mock_val = workstations.WorkstationCluster(name='name_value') + assert arg == mock_val + arg = args[0].workstation_cluster_id + mock_val = 'workstation_cluster_id_value' + assert arg == mock_val + + +def test_create_workstation_cluster_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_cluster( + workstations.CreateWorkstationClusterRequest(), + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_value', + ) + +@pytest.mark.asyncio +async def test_create_workstation_cluster_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_cluster), + '__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_workstation_cluster( + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].workstation_cluster + mock_val = workstations.WorkstationCluster(name='name_value') + assert arg == mock_val + arg = args[0].workstation_cluster_id + mock_val = 'workstation_cluster_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_workstation_cluster_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_cluster( + workstations.CreateWorkstationClusterRequest(), + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationClusterRequest, + dict, +]) +def test_update_workstation_cluster(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_workstation_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_cluster), + '__call__') as call: + client.update_workstation_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationClusterRequest() + +@pytest.mark.asyncio +async def test_update_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationClusterRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__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_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_workstation_cluster_async_from_dict(): + await test_update_workstation_cluster_async(request_type=dict) + + +def test_update_workstation_cluster_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationClusterRequest() + + request.workstation_cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation_cluster.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_workstation_cluster_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationClusterRequest() + + request.workstation_cluster.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation_cluster.name=name_value', + ) in kw['metadata'] + + +def test_update_workstation_cluster_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__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_workstation_cluster( + workstation_cluster=workstations.WorkstationCluster(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].workstation_cluster + mock_val = workstations.WorkstationCluster(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_workstation_cluster_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_cluster( + workstations.UpdateWorkstationClusterRequest(), + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_workstation_cluster_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_cluster), + '__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_workstation_cluster( + workstation_cluster=workstations.WorkstationCluster(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].workstation_cluster + mock_val = workstations.WorkstationCluster(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_workstation_cluster_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_cluster( + workstations.UpdateWorkstationClusterRequest(), + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationClusterRequest, + dict, +]) +def test_delete_workstation_cluster(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_workstation_cluster_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_cluster), + '__call__') as call: + client.delete_workstation_cluster() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationClusterRequest() + +@pytest.mark.asyncio +async def test_delete_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationClusterRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_cluster), + '__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_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_workstation_cluster_async_from_dict(): + await test_delete_workstation_cluster_async(request_type=dict) + + +def test_delete_workstation_cluster_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationClusterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_workstation_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_cluster_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__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_workstation_cluster( + 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_workstation_cluster_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_cluster( + workstations.DeleteWorkstationClusterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_workstation_cluster_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_cluster), + '__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_workstation_cluster( + 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_workstation_cluster_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_cluster( + workstations.DeleteWorkstationClusterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationConfigRequest, + dict, +]) +def test_get_workstation_config(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationConfig( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + degraded=True, + enable_audit_agent=True, + ) + response = client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.degraded is True + assert response.enable_audit_agent is True + + +def test_get_workstation_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_config), + '__call__') as call: + client.get_workstation_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationConfigRequest() + +@pytest.mark.asyncio +async def test_get_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationConfigRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + degraded=True, + enable_audit_agent=True, + )) + response = await client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.degraded is True + assert response.enable_audit_agent is True + + +@pytest.mark.asyncio +async def test_get_workstation_config_async_from_dict(): + await test_get_workstation_config_async(request_type=dict) + + +def test_get_workstation_config_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + call.return_value = workstations.WorkstationConfig() + client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_workstation_config_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig()) + await client.get_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_workstation_config_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_workstation_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_workstation_config_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_config( + workstations.GetWorkstationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_workstation_config_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.WorkstationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_workstation_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_workstation_config_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_config( + workstations.GetWorkstationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationConfigsRequest, + dict, +]) +def test_list_workstation_configs(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workstation_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_configs), + '__call__') as call: + client.list_workstation_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationConfigsRequest() + +@pytest.mark.asyncio +async def test_list_workstation_configs_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationConfigsRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_workstation_configs_async_from_dict(): + await test_list_workstation_configs_async(request_type=dict) + + +def test_list_workstation_configs_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + call.return_value = workstations.ListWorkstationConfigsResponse() + client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_workstation_configs_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse()) + await client.list_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_workstation_configs_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_workstation_configs( + 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_workstation_configs_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_configs( + workstations.ListWorkstationConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_workstation_configs_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_workstation_configs( + 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_workstation_configs_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_configs( + workstations.ListWorkstationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_workstation_configs_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstation_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_workstation_configs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.WorkstationConfig) + for i in results) +def test_list_workstation_configs_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstation_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_workstation_configs(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_workstation_configs_async_pager(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_workstation_configs(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, workstations.WorkstationConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_workstation_configs_async_pages(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstation_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_workstation_configs(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + workstations.ListUsableWorkstationConfigsRequest, + dict, +]) +def test_list_usable_workstation_configs(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_usable_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListUsableWorkstationConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_usable_workstation_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_usable_workstation_configs), + '__call__') as call: + client.list_usable_workstation_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListUsableWorkstationConfigsRequest() + +@pytest.mark.asyncio +async def test_list_usable_workstation_configs_async(transport: str = 'grpc_asyncio', request_type=workstations.ListUsableWorkstationConfigsRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_usable_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListUsableWorkstationConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_usable_workstation_configs_async_from_dict(): + await test_list_usable_workstation_configs_async(request_type=dict) + + +def test_list_usable_workstation_configs_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListUsableWorkstationConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + call.return_value = workstations.ListUsableWorkstationConfigsResponse() + client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_usable_workstation_configs_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListUsableWorkstationConfigsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse()) + await client.list_usable_workstation_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_usable_workstation_configs_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_usable_workstation_configs( + 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_usable_workstation_configs_flattened_error(): + client = WorkstationsClient( + credentials=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_usable_workstation_configs( + workstations.ListUsableWorkstationConfigsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_usable_workstation_configs_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_usable_workstation_configs( + 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_usable_workstation_configs_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_usable_workstation_configs( + workstations.ListUsableWorkstationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_usable_workstation_configs_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_usable_workstation_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_usable_workstation_configs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.WorkstationConfig) + for i in results) +def test_list_usable_workstation_configs_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_usable_workstation_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_usable_workstation_configs(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_usable_workstation_configs_async_pager(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_usable_workstation_configs(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, workstations.WorkstationConfig) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_usable_workstation_configs_async_pages(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstation_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_usable_workstation_configs(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + workstations.CreateWorkstationConfigRequest, + dict, +]) +def test_create_workstation_config(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_workstation_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_config), + '__call__') as call: + client.create_workstation_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationConfigRequest() + +@pytest.mark.asyncio +async def test_create_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationConfigRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__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_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_workstation_config_async_from_dict(): + await test_create_workstation_config_async(request_type=dict) + + +def test_create_workstation_config_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_workstation_config_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_workstation_config_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__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_workstation_config( + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].workstation_config + mock_val = workstations.WorkstationConfig(name='name_value') + assert arg == mock_val + arg = args[0].workstation_config_id + mock_val = 'workstation_config_id_value' + assert arg == mock_val + + +def test_create_workstation_config_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_config( + workstations.CreateWorkstationConfigRequest(), + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_value', + ) + +@pytest.mark.asyncio +async def test_create_workstation_config_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation_config), + '__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_workstation_config( + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].workstation_config + mock_val = workstations.WorkstationConfig(name='name_value') + assert arg == mock_val + arg = args[0].workstation_config_id + mock_val = 'workstation_config_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_workstation_config_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_config( + workstations.CreateWorkstationConfigRequest(), + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationConfigRequest, + dict, +]) +def test_update_workstation_config(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_workstation_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_config), + '__call__') as call: + client.update_workstation_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationConfigRequest() + +@pytest.mark.asyncio +async def test_update_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationConfigRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__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_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_workstation_config_async_from_dict(): + await test_update_workstation_config_async(request_type=dict) + + +def test_update_workstation_config_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationConfigRequest() + + request.workstation_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_workstation_config_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationConfigRequest() + + request.workstation_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation_config.name=name_value', + ) in kw['metadata'] + + +def test_update_workstation_config_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__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_workstation_config( + workstation_config=workstations.WorkstationConfig(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].workstation_config + mock_val = workstations.WorkstationConfig(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_workstation_config_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_config( + workstations.UpdateWorkstationConfigRequest(), + workstation_config=workstations.WorkstationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_workstation_config_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation_config), + '__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_workstation_config( + workstation_config=workstations.WorkstationConfig(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].workstation_config + mock_val = workstations.WorkstationConfig(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_workstation_config_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_config( + workstations.UpdateWorkstationConfigRequest(), + workstation_config=workstations.WorkstationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationConfigRequest, + dict, +]) +def test_delete_workstation_config(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_workstation_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation_config), + '__call__') as call: + client.delete_workstation_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationConfigRequest() + +@pytest.mark.asyncio +async def test_delete_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationConfigRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation_config), + '__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_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_workstation_config_async_from_dict(): + await test_delete_workstation_config_async(request_type=dict) + + +def test_delete_workstation_config_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_workstation_config_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_workstation_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_workstation_config_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__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_workstation_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_workstation_config_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation_config( + workstations.DeleteWorkstationConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_workstation_config_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation_config), + '__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_workstation_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_workstation_config_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation_config( + workstations.DeleteWorkstationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationRequest, + dict, +]) +def test_get_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.Workstation( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + state=workstations.Workstation.State.STATE_STARTING, + host='host_value', + ) + response = client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.Workstation) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.state == workstations.Workstation.State.STATE_STARTING + assert response.host == 'host_value' + + +def test_get_workstation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation), + '__call__') as call: + client.get_workstation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationRequest() + +@pytest.mark.asyncio +async def test_get_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + state=workstations.Workstation.State.STATE_STARTING, + host='host_value', + )) + response = await client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GetWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.Workstation) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.state == workstations.Workstation.State.STATE_STARTING + assert response.host == 'host_value' + + +@pytest.mark.asyncio +async def test_get_workstation_async_from_dict(): + await test_get_workstation_async(request_type=dict) + + +def test_get_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + call.return_value = workstations.Workstation() + client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GetWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation()) + await client.get_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.Workstation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_workstation( + 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_workstation_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation( + workstations.GetWorkstationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.Workstation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_workstation( + 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_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation( + workstations.GetWorkstationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationsRequest, + dict, +]) +def test_list_workstations(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workstations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstations), + '__call__') as call: + client.list_workstations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationsRequest() + +@pytest.mark.asyncio +async def test_list_workstations_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationsRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListWorkstationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_workstations_async_from_dict(): + await test_list_workstations_async(request_type=dict) + + +def test_list_workstations_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + call.return_value = workstations.ListWorkstationsResponse() + client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_workstations_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListWorkstationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse()) + await client.list_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_workstations_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_workstations( + 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_workstations_flattened_error(): + client = WorkstationsClient( + credentials=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_workstations( + workstations.ListWorkstationsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_workstations_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListWorkstationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_workstations( + 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_workstations_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstations( + workstations.ListWorkstationsRequest(), + parent='parent_value', + ) + + +def test_list_workstations_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_workstations(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.Workstation) + for i in results) +def test_list_workstations_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_workstations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_workstations(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_workstations_async_pager(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_workstations(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, workstations.Workstation) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_workstations_async_pages(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workstations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_workstations(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + workstations.ListUsableWorkstationsRequest, + dict, +]) +def test_list_usable_workstations(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_usable_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListUsableWorkstationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_usable_workstations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_usable_workstations), + '__call__') as call: + client.list_usable_workstations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListUsableWorkstationsRequest() + +@pytest.mark.asyncio +async def test_list_usable_workstations_async(transport: str = 'grpc_asyncio', request_type=workstations.ListUsableWorkstationsRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_usable_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.ListUsableWorkstationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_usable_workstations_async_from_dict(): + await test_list_usable_workstations_async(request_type=dict) + + +def test_list_usable_workstations_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListUsableWorkstationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + call.return_value = workstations.ListUsableWorkstationsResponse() + client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_usable_workstations_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.ListUsableWorkstationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse()) + await client.list_usable_workstations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_usable_workstations_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_usable_workstations( + 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_usable_workstations_flattened_error(): + client = WorkstationsClient( + credentials=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_usable_workstations( + workstations.ListUsableWorkstationsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_usable_workstations_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.ListUsableWorkstationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_usable_workstations( + 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_usable_workstations_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_usable_workstations( + workstations.ListUsableWorkstationsRequest(), + parent='parent_value', + ) + + +def test_list_usable_workstations_pager(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_usable_workstations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_usable_workstations(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.Workstation) + for i in results) +def test_list_usable_workstations_pages(transport_name: str = "grpc"): + client = WorkstationsClient( + 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_usable_workstations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_usable_workstations(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_usable_workstations_async_pager(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_usable_workstations(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, workstations.Workstation) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_usable_workstations_async_pages(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_usable_workstations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_usable_workstations(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + workstations.CreateWorkstationRequest, + dict, +]) +def test_create_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_workstation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation), + '__call__') as call: + client.create_workstation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationRequest() + +@pytest.mark.asyncio +async def test_create_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__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_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.CreateWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_workstation_async_from_dict(): + await test_create_workstation_async(request_type=dict) + + +def test_create_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.CreateWorkstationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__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_workstation( + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].workstation + mock_val = workstations.Workstation(name='name_value') + assert arg == mock_val + arg = args[0].workstation_id + mock_val = 'workstation_id_value' + assert arg == mock_val + + +def test_create_workstation_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation( + workstations.CreateWorkstationRequest(), + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_value', + ) + +@pytest.mark.asyncio +async def test_create_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_workstation), + '__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_workstation( + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].workstation + mock_val = workstations.Workstation(name='name_value') + assert arg == mock_val + arg = args[0].workstation_id + mock_val = 'workstation_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation( + workstations.CreateWorkstationRequest(), + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationRequest, + dict, +]) +def test_update_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_workstation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation), + '__call__') as call: + client.update_workstation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationRequest() + +@pytest.mark.asyncio +async def test_update_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__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_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.UpdateWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_workstation_async_from_dict(): + await test_update_workstation_async(request_type=dict) + + +def test_update_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationRequest() + + request.workstation.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.UpdateWorkstationRequest() + + request.workstation.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation.name=name_value', + ) in kw['metadata'] + + +def test_update_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__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_workstation( + workstation=workstations.Workstation(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].workstation + mock_val = workstations.Workstation(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_workstation_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation( + workstations.UpdateWorkstationRequest(), + workstation=workstations.Workstation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_workstation), + '__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_workstation( + workstation=workstations.Workstation(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].workstation + mock_val = workstations.Workstation(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_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation( + workstations.UpdateWorkstationRequest(), + workstation=workstations.Workstation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationRequest, + dict, +]) +def test_delete_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_workstation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=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_workstation), + '__call__') as call: + client.delete_workstation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationRequest() + +@pytest.mark.asyncio +async def test_delete_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_workstation), + '__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_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.DeleteWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_workstation_async_from_dict(): + await test_delete_workstation_async(request_type=dict) + + +def test_delete_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.DeleteWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__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_workstation( + 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_workstation_flattened_error(): + client = WorkstationsClient( + credentials=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_workstation( + workstations.DeleteWorkstationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_workstation), + '__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_workstation( + 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_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + 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_workstation( + workstations.DeleteWorkstationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.StartWorkstationRequest, + dict, +]) +def test_start_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.start_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.StartWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_start_workstation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + client.start_workstation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.StartWorkstationRequest() + +@pytest.mark.asyncio +async def test_start_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.StartWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__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.start_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.StartWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_start_workstation_async_from_dict(): + await test_start_workstation_async(request_type=dict) + + +def test_start_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.StartWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.start_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_start_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.StartWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.start_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_start_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__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.start_workstation( + 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_start_workstation_flattened_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.start_workstation( + workstations.StartWorkstationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_start_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_workstation), + '__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.start_workstation( + 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_start_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + 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.start_workstation( + workstations.StartWorkstationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.StopWorkstationRequest, + dict, +]) +def test_stop_workstation(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.stop_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.StopWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_stop_workstation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + client.stop_workstation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.StopWorkstationRequest() + +@pytest.mark.asyncio +async def test_stop_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.StopWorkstationRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__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.stop_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.StopWorkstationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_stop_workstation_async_from_dict(): + await test_stop_workstation_async(request_type=dict) + + +def test_stop_workstation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.StopWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.stop_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_stop_workstation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.StopWorkstationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.stop_workstation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_stop_workstation_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__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.stop_workstation( + 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_stop_workstation_flattened_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.stop_workstation( + workstations.StopWorkstationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_stop_workstation_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_workstation), + '__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.stop_workstation( + 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_stop_workstation_flattened_error_async(): + client = WorkstationsAsyncClient( + 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.stop_workstation( + workstations.StopWorkstationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GenerateAccessTokenRequest, + dict, +]) +def test_generate_access_token(request_type, transport: str = 'grpc'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.GenerateAccessTokenResponse( + access_token='access_token_value', + ) + response = client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GenerateAccessTokenRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.GenerateAccessTokenResponse) + assert response.access_token == 'access_token_value' + + +def test_generate_access_token_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + client.generate_access_token() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GenerateAccessTokenRequest() + +@pytest.mark.asyncio +async def test_generate_access_token_async(transport: str = 'grpc_asyncio', request_type=workstations.GenerateAccessTokenRequest): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse( + access_token='access_token_value', + )) + response = await client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == workstations.GenerateAccessTokenRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.GenerateAccessTokenResponse) + assert response.access_token == 'access_token_value' + + +@pytest.mark.asyncio +async def test_generate_access_token_async_from_dict(): + await test_generate_access_token_async(request_type=dict) + + +def test_generate_access_token_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GenerateAccessTokenRequest() + + request.workstation = 'workstation_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + call.return_value = workstations.GenerateAccessTokenResponse() + client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation=workstation_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_generate_access_token_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = workstations.GenerateAccessTokenRequest() + + request.workstation = 'workstation_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse()) + await client.generate_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'workstation=workstation_value', + ) in kw['metadata'] + + +def test_generate_access_token_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.GenerateAccessTokenResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.generate_access_token( + workstation='workstation_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].workstation + mock_val = 'workstation_value' + assert arg == mock_val + + +def test_generate_access_token_flattened_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_access_token( + workstations.GenerateAccessTokenRequest(), + workstation='workstation_value', + ) + +@pytest.mark.asyncio +async def test_generate_access_token_flattened_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_access_token), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = workstations.GenerateAccessTokenResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.generate_access_token( + workstation='workstation_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].workstation + mock_val = 'workstation_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_generate_access_token_flattened_error_async(): + client = WorkstationsAsyncClient( + 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.generate_access_token( + workstations.GenerateAccessTokenRequest(), + workstation='workstation_value', + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationClusterRequest, + dict, +]) +def test_get_workstation_cluster_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationCluster( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + network='network_value', + subnetwork='subnetwork_value', + control_plane_ip='control_plane_ip_value', + degraded=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.WorkstationCluster.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_workstation_cluster(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationCluster) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.network == 'network_value' + assert response.subnetwork == 'subnetwork_value' + assert response.control_plane_ip == 'control_plane_ip_value' + assert response.degraded is True + + +def test_get_workstation_cluster_rest_required_fields(request_type=workstations.GetWorkstationClusterRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_cluster._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_workstation_cluster._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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationCluster() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # 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 = workstations.WorkstationCluster.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_workstation_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_workstation_cluster_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_workstation_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_workstation_cluster_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation_cluster") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.GetWorkstationClusterRequest.pb(workstations.GetWorkstationClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = workstations.WorkstationCluster.to_json(workstations.WorkstationCluster()) + + request = workstations.GetWorkstationClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.WorkstationCluster() + + client.get_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_workstation_cluster_rest_bad_request(transport: str = 'rest', request_type=workstations.GetWorkstationClusterRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_workstation_cluster(request) + + +def test_get_workstation_cluster_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationCluster() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.WorkstationCluster.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_workstation_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) + + +def test_get_workstation_cluster_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_cluster( + workstations.GetWorkstationClusterRequest(), + name='name_value', + ) + + +def test_get_workstation_cluster_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationClustersRequest, + dict, +]) +def test_list_workstation_clusters_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationClustersResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListWorkstationClustersResponse.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_workstation_clusters(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationClustersPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workstation_clusters_rest_required_fields(request_type=workstations.ListWorkstationClustersRequest): + transport_class = transports.WorkstationsRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstation_clusters._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstation_clusters._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationClustersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # 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 = workstations.ListWorkstationClustersResponse.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_workstation_clusters(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_workstation_clusters_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_workstation_clusters._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_workstation_clusters_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstation_clusters") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstation_clusters") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListWorkstationClustersRequest.pb(workstations.ListWorkstationClustersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = workstations.ListWorkstationClustersResponse.to_json(workstations.ListWorkstationClustersResponse()) + + request = workstations.ListWorkstationClustersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListWorkstationClustersResponse() + + client.list_workstation_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_workstation_clusters_rest_bad_request(transport: str = 'rest', request_type=workstations.ListWorkstationClustersRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_workstation_clusters(request) + + +def test_list_workstation_clusters_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationClustersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListWorkstationClustersResponse.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_workstation_clusters(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*}/workstationClusters" % client.transport._host, args[1]) + + +def test_list_workstation_clusters_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_clusters( + workstations.ListWorkstationClustersRequest(), + parent='parent_value', + ) + + +def test_list_workstation_clusters_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[], + next_page_token='def', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationClustersResponse( + workstation_clusters=[ + workstations.WorkstationCluster(), + workstations.WorkstationCluster(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListWorkstationClustersResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_workstation_clusters(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.WorkstationCluster) + for i in results) + + pages = list(client.list_workstation_clusters(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", [ + workstations.CreateWorkstationClusterRequest, + dict, +]) +def test_create_workstation_cluster_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["workstation_cluster"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + 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_workstation_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_workstation_cluster_rest_required_fields(request_type=workstations.CreateWorkstationClusterRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["workstation_cluster_id"] = "" + 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 "workstationClusterId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "workstationClusterId" in jsonified_request + assert jsonified_request["workstationClusterId"] == request_init["workstation_cluster_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["workstationClusterId"] = 'workstation_cluster_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_cluster._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", "workstation_cluster_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "workstationClusterId" in jsonified_request + assert jsonified_request["workstationClusterId"] == 'workstation_cluster_id_value' + + client = WorkstationsClient( + 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_workstation_cluster(request) + + expected_params = [ + ( + "workstationClusterId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_workstation_cluster_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_workstation_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("validateOnly", "workstationClusterId", )) & set(("parent", "workstationClusterId", "workstationCluster", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_workstation_cluster_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation_cluster") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.CreateWorkstationClusterRequest.pb(workstations.CreateWorkstationClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.CreateWorkstationClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_workstation_cluster_rest_bad_request(transport: str = 'rest', request_type=workstations.CreateWorkstationClusterRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["workstation_cluster"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_workstation_cluster(request) + + +def test_create_workstation_cluster_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_workstation_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*}/workstationClusters" % client.transport._host, args[1]) + + +def test_create_workstation_cluster_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_cluster( + workstations.CreateWorkstationClusterRequest(), + parent='parent_value', + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + workstation_cluster_id='workstation_cluster_id_value', + ) + + +def test_create_workstation_cluster_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationClusterRequest, + dict, +]) +def test_update_workstation_cluster_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} + request_init["workstation_cluster"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + 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_workstation_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_workstation_cluster_rest_required_fields(request_type=workstations.UpdateWorkstationClusterRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_cluster._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_workstation_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WorkstationsClient( + 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_workstation_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_workstation_cluster_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_workstation_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstationCluster", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_workstation_cluster_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation_cluster") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.UpdateWorkstationClusterRequest.pb(workstations.UpdateWorkstationClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.UpdateWorkstationClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_workstation_cluster_rest_bad_request(transport: str = 'rest', request_type=workstations.UpdateWorkstationClusterRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} + request_init["workstation_cluster"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_workstation_cluster(request) + + +def test_update_workstation_cluster_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + 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 = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + workstation_cluster=workstations.WorkstationCluster(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_workstation_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{workstation_cluster.name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) + + +def test_update_workstation_cluster_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_cluster( + workstations.UpdateWorkstationClusterRequest(), + workstation_cluster=workstations.WorkstationCluster(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_workstation_cluster_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationClusterRequest, + dict, +]) +def test_delete_workstation_cluster_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_workstation_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_workstation_cluster_rest_required_fields(request_type=workstations.DeleteWorkstationClusterRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_cluster._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_workstation_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag", "force", "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 = WorkstationsClient( + 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_workstation_cluster(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_workstation_cluster_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_workstation_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "force", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_workstation_cluster_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation_cluster") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation_cluster") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.DeleteWorkstationClusterRequest.pb(workstations.DeleteWorkstationClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.DeleteWorkstationClusterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_workstation_cluster_rest_bad_request(transport: str = 'rest', request_type=workstations.DeleteWorkstationClusterRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_workstation_cluster(request) + + +def test_delete_workstation_cluster_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_workstation_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) + + +def test_delete_workstation_cluster_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_cluster( + workstations.DeleteWorkstationClusterRequest(), + name='name_value', + ) + + +def test_delete_workstation_cluster_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationConfigRequest, + dict, +]) +def test_get_workstation_config_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationConfig( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + degraded=True, + enable_audit_agent=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.WorkstationConfig.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_workstation_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.WorkstationConfig) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.degraded is True + assert response.enable_audit_agent is True + + +def test_get_workstation_config_rest_required_fields(request_type=workstations.GetWorkstationConfigRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_workstation_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # 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 = workstations.WorkstationConfig.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_workstation_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_workstation_config_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_workstation_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_workstation_config_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation_config") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.GetWorkstationConfigRequest.pb(workstations.GetWorkstationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = workstations.WorkstationConfig.to_json(workstations.WorkstationConfig()) + + request = workstations.GetWorkstationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.WorkstationConfig() + + client.get_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_workstation_config_rest_bad_request(transport: str = 'rest', request_type=workstations.GetWorkstationConfigRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_workstation_config(request) + + +def test_get_workstation_config_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.WorkstationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.WorkstationConfig.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_workstation_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) + + +def test_get_workstation_config_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_config( + workstations.GetWorkstationConfigRequest(), + name='name_value', + ) + + +def test_get_workstation_config_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationConfigsRequest, + dict, +]) +def test_list_workstation_configs_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListWorkstationConfigsResponse.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_workstation_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workstation_configs_rest_required_fields(request_type=workstations.ListWorkstationConfigsRequest): + transport_class = transports.WorkstationsRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstation_configs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstation_configs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # 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 = workstations.ListWorkstationConfigsResponse.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_workstation_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_workstation_configs_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_workstation_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_workstation_configs_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstation_configs") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstation_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListWorkstationConfigsRequest.pb(workstations.ListWorkstationConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = workstations.ListWorkstationConfigsResponse.to_json(workstations.ListWorkstationConfigsResponse()) + + request = workstations.ListWorkstationConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListWorkstationConfigsResponse() + + client.list_workstation_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_workstation_configs_rest_bad_request(transport: str = 'rest', request_type=workstations.ListWorkstationConfigsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_workstation_configs(request) + + +def test_list_workstation_configs_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListWorkstationConfigsResponse.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_workstation_configs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs" % client.transport._host, args[1]) + + +def test_list_workstation_configs_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_configs( + workstations.ListWorkstationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_workstation_configs_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListWorkstationConfigsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + pager = client.list_workstation_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.WorkstationConfig) + for i in results) + + pages = list(client.list_workstation_configs(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", [ + workstations.ListUsableWorkstationConfigsRequest, + dict, +]) +def test_list_usable_workstation_configs_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationConfigsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListUsableWorkstationConfigsResponse.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_usable_workstation_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_usable_workstation_configs_rest_required_fields(request_type=workstations.ListUsableWorkstationConfigsRequest): + transport_class = transports.WorkstationsRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_usable_workstation_configs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_usable_workstation_configs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # 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 = workstations.ListUsableWorkstationConfigsResponse.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_usable_workstation_configs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_usable_workstation_configs_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_usable_workstation_configs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_usable_workstation_configs_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_usable_workstation_configs") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_usable_workstation_configs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListUsableWorkstationConfigsRequest.pb(workstations.ListUsableWorkstationConfigsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = workstations.ListUsableWorkstationConfigsResponse.to_json(workstations.ListUsableWorkstationConfigsResponse()) + + request = workstations.ListUsableWorkstationConfigsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListUsableWorkstationConfigsResponse() + + client.list_usable_workstation_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_usable_workstation_configs_rest_bad_request(transport: str = 'rest', request_type=workstations.ListUsableWorkstationConfigsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_usable_workstation_configs(request) + + +def test_list_usable_workstation_configs_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListUsableWorkstationConfigsResponse.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_usable_workstation_configs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs:listUsable" % client.transport._host, args[1]) + + +def test_list_usable_workstation_configs_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_usable_workstation_configs( + workstations.ListUsableWorkstationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_usable_workstation_configs_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationConfigsResponse( + workstation_configs=[ + workstations.WorkstationConfig(), + workstations.WorkstationConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListUsableWorkstationConfigsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + pager = client.list_usable_workstation_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.WorkstationConfig) + for i in results) + + pages = list(client.list_usable_workstation_configs(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", [ + workstations.CreateWorkstationConfigRequest, + dict, +]) +def test_create_workstation_config_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request_init["workstation_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792, 'accelerators': [{'type_': 'type__value', 'count': 553}]}}, 'persistent_directories': [{'mount_path': 'mount_path_value', 'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'readiness_checks': [{'path': 'path_value', 'port': 453}], 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}], 'enable_audit_agent': True} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + 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_workstation_config(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_workstation_config_rest_required_fields(request_type=workstations.CreateWorkstationConfigRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["workstation_config_id"] = "" + 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 "workstationConfigId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "workstationConfigId" in jsonified_request + assert jsonified_request["workstationConfigId"] == request_init["workstation_config_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["workstationConfigId"] = 'workstation_config_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_config._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", "workstation_config_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "workstationConfigId" in jsonified_request + assert jsonified_request["workstationConfigId"] == 'workstation_config_id_value' + + client = WorkstationsClient( + 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_workstation_config(request) + + expected_params = [ + ( + "workstationConfigId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_workstation_config_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_workstation_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("validateOnly", "workstationConfigId", )) & set(("parent", "workstationConfigId", "workstationConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_workstation_config_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation_config") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.CreateWorkstationConfigRequest.pb(workstations.CreateWorkstationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.CreateWorkstationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_workstation_config_rest_bad_request(transport: str = 'rest', request_type=workstations.CreateWorkstationConfigRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + request_init["workstation_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792, 'accelerators': [{'type_': 'type__value', 'count': 553}]}}, 'persistent_directories': [{'mount_path': 'mount_path_value', 'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'readiness_checks': [{'path': 'path_value', 'port': 453}], 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}], 'enable_audit_agent': True} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_workstation_config(request) + + +def test_create_workstation_config_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_workstation_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs" % client.transport._host, args[1]) + + +def test_create_workstation_config_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_config( + workstations.CreateWorkstationConfigRequest(), + parent='parent_value', + workstation_config=workstations.WorkstationConfig(name='name_value'), + workstation_config_id='workstation_config_id_value', + ) + + +def test_create_workstation_config_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationConfigRequest, + dict, +]) +def test_update_workstation_config_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} + request_init["workstation_config"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792, 'accelerators': [{'type_': 'type__value', 'count': 553}]}}, 'persistent_directories': [{'mount_path': 'mount_path_value', 'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'readiness_checks': [{'path': 'path_value', 'port': 453}], 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}], 'enable_audit_agent': True} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + 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_workstation_config(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_workstation_config_rest_required_fields(request_type=workstations.UpdateWorkstationConfigRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_workstation_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WorkstationsClient( + 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_workstation_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_workstation_config_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_workstation_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstationConfig", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_workstation_config_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation_config") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.UpdateWorkstationConfigRequest.pb(workstations.UpdateWorkstationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.UpdateWorkstationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_workstation_config_rest_bad_request(transport: str = 'rest', request_type=workstations.UpdateWorkstationConfigRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} + request_init["workstation_config"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792, 'accelerators': [{'type_': 'type__value', 'count': 553}]}}, 'persistent_directories': [{'mount_path': 'mount_path_value', 'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'readiness_checks': [{'path': 'path_value', 'port': 453}], 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}], 'enable_audit_agent': True} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_workstation_config(request) + + +def test_update_workstation_config_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + 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 = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + workstation_config=workstations.WorkstationConfig(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_workstation_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{workstation_config.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) + + +def test_update_workstation_config_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_config( + workstations.UpdateWorkstationConfigRequest(), + workstation_config=workstations.WorkstationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_workstation_config_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationConfigRequest, + dict, +]) +def test_delete_workstation_config_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = 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_workstation_config(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_workstation_config_rest_required_fields(request_type=workstations.DeleteWorkstationConfigRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_workstation_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag", "force", "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 = WorkstationsClient( + 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_workstation_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_workstation_config_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_workstation_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "force", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_workstation_config_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation_config") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.DeleteWorkstationConfigRequest.pb(workstations.DeleteWorkstationConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.DeleteWorkstationConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_workstation_config_rest_bad_request(transport: str = 'rest', request_type=workstations.DeleteWorkstationConfigRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_workstation_config(request) + + +def test_delete_workstation_config_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_workstation_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) + + +def test_delete_workstation_config_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation_config( + workstations.DeleteWorkstationConfigRequest(), + name='name_value', + ) + + +def test_delete_workstation_config_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GetWorkstationRequest, + dict, +]) +def test_get_workstation_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.Workstation( + name='name_value', + display_name='display_name_value', + uid='uid_value', + reconciling=True, + etag='etag_value', + state=workstations.Workstation.State.STATE_STARTING, + host='host_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.Workstation.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_workstation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.Workstation) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.uid == 'uid_value' + assert response.reconciling is True + assert response.etag == 'etag_value' + assert response.state == workstations.Workstation.State.STATE_STARTING + assert response.host == 'host_value' + + +def test_get_workstation_rest_required_fields(request_type=workstations.GetWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation._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_workstation._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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.Workstation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # 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 = workstations.Workstation.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_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.GetWorkstationRequest.pb(workstations.GetWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = workstations.Workstation.to_json(workstations.Workstation()) + + request = workstations.GetWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.Workstation() + + client.get_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.GetWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_workstation(request) + + +def test_get_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.Workstation() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.Workstation.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_workstation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) + + +def test_get_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation( + workstations.GetWorkstationRequest(), + name='name_value', + ) + + +def test_get_workstation_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.ListWorkstationsRequest, + dict, +]) +def test_list_workstations_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListWorkstationsResponse.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_workstations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkstationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_workstations_rest_required_fields(request_type=workstations.ListWorkstationsRequest): + transport_class = transports.WorkstationsRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstations._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # 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 = workstations.ListWorkstationsResponse.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_workstations(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_workstations_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_workstations._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_workstations_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstations") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListWorkstationsRequest.pb(workstations.ListWorkstationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = workstations.ListWorkstationsResponse.to_json(workstations.ListWorkstationsResponse()) + + request = workstations.ListWorkstationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListWorkstationsResponse() + + client.list_workstations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_workstations_rest_bad_request(transport: str = 'rest', request_type=workstations.ListWorkstationsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_workstations(request) + + +def test_list_workstations_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListWorkstationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListWorkstationsResponse.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_workstations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations" % client.transport._host, args[1]) + + +def test_list_workstations_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstations( + workstations.ListWorkstationsRequest(), + parent='parent_value', + ) + + +def test_list_workstations_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListWorkstationsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + pager = client.list_workstations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.Workstation) + for i in results) + + pages = list(client.list_workstations(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", [ + workstations.ListUsableWorkstationsRequest, + dict, +]) +def test_list_usable_workstations_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListUsableWorkstationsResponse.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_usable_workstations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsableWorkstationsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_usable_workstations_rest_required_fields(request_type=workstations.ListUsableWorkstationsRequest): + transport_class = transports.WorkstationsRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_usable_workstations._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_usable_workstations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # 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 = workstations.ListUsableWorkstationsResponse.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_usable_workstations(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_usable_workstations_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_usable_workstations._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_usable_workstations_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_usable_workstations") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_usable_workstations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.ListUsableWorkstationsRequest.pb(workstations.ListUsableWorkstationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = workstations.ListUsableWorkstationsResponse.to_json(workstations.ListUsableWorkstationsResponse()) + + request = workstations.ListUsableWorkstationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.ListUsableWorkstationsResponse() + + client.list_usable_workstations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_usable_workstations_rest_bad_request(transport: str = 'rest', request_type=workstations.ListUsableWorkstationsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_usable_workstations(request) + + +def test_list_usable_workstations_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.ListUsableWorkstationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.ListUsableWorkstationsResponse.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_usable_workstations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations:listUsable" % client.transport._host, args[1]) + + +def test_list_usable_workstations_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_usable_workstations( + workstations.ListUsableWorkstationsRequest(), + parent='parent_value', + ) + + +def test_list_usable_workstations_rest_pager(transport: str = 'rest'): + client = WorkstationsClient( + 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 = ( + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + workstations.Workstation(), + ], + next_page_token='abc', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[], + next_page_token='def', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + ], + next_page_token='ghi', + ), + workstations.ListUsableWorkstationsResponse( + workstations=[ + workstations.Workstation(), + workstations.Workstation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(workstations.ListUsableWorkstationsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + pager = client.list_usable_workstations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, workstations.Workstation) + for i in results) + + pages = list(client.list_usable_workstations(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", [ + workstations.CreateWorkstationRequest, + dict, +]) +def test_create_workstation_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request_init["workstation"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_value', 'env': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + 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_workstation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_workstation_rest_required_fields(request_type=workstations.CreateWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["workstation_id"] = "" + 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 "workstationId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "workstationId" in jsonified_request + assert jsonified_request["workstationId"] == request_init["workstation_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["workstationId"] = 'workstation_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation._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", "workstation_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "workstationId" in jsonified_request + assert jsonified_request["workstationId"] == 'workstation_id_value' + + client = WorkstationsClient( + 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_workstation(request) + + expected_params = [ + ( + "workstationId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("validateOnly", "workstationId", )) & set(("parent", "workstationId", "workstation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.CreateWorkstationRequest.pb(workstations.CreateWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.CreateWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.CreateWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request_init["workstation"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_value', 'env': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_workstation(request) + + +def test_create_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_workstation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations" % client.transport._host, args[1]) + + +def test_create_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation( + workstations.CreateWorkstationRequest(), + parent='parent_value', + workstation=workstations.Workstation(name='name_value'), + workstation_id='workstation_id_value', + ) + + +def test_create_workstation_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.UpdateWorkstationRequest, + dict, +]) +def test_update_workstation_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} + request_init["workstation"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_value', 'env': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + 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_workstation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_workstation_rest_required_fields(request_type=workstations.UpdateWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation._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_workstation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WorkstationsClient( + 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_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstation", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.UpdateWorkstationRequest.pb(workstations.UpdateWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.UpdateWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.UpdateWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} + request_init["workstation"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_value', 'env': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the 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_workstation(request) + + +def test_update_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + 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 = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} + + # get truthy value for each flattened field + mock_args = dict( + workstation=workstations.Workstation(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_workstation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{workstation.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) + + +def test_update_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation( + workstations.UpdateWorkstationRequest(), + workstation=workstations.Workstation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_workstation_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.DeleteWorkstationRequest, + dict, +]) +def test_delete_workstation_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = 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_workstation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_workstation_rest_required_fields(request_type=workstations.DeleteWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + 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_workstation._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_workstation._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 = WorkstationsClient( + 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_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag", "validateOnly", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.DeleteWorkstationRequest.pb(workstations.DeleteWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.DeleteWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.DeleteWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_workstation(request) + + +def test_delete_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_workstation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) + + +def test_delete_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.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_workstation( + workstations.DeleteWorkstationRequest(), + name='name_value', + ) + + +def test_delete_workstation_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.StartWorkstationRequest, + dict, +]) +def test_start_workstation_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = 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.start_workstation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_start_workstation_rest_required_fields(request_type=workstations.StartWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + 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()).start_workstation._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()).start_workstation._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 = WorkstationsClient( + 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.start_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_start_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.start_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_start_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_start_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_start_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.StartWorkstationRequest.pb(workstations.StartWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.StartWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.start_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_start_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.StartWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.start_workstation(request) + + +def test_start_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.start_workstation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:start" % client.transport._host, args[1]) + + +def test_start_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.start_workstation( + workstations.StartWorkstationRequest(), + name='name_value', + ) + + +def test_start_workstation_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.StopWorkstationRequest, + dict, +]) +def test_stop_workstation_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = 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.stop_workstation(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_stop_workstation_rest_required_fields(request_type=workstations.StopWorkstationRequest): + transport_class = transports.WorkstationsRestTransport + + 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()).stop_workstation._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()).stop_workstation._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 = WorkstationsClient( + 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.stop_workstation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_stop_workstation_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.stop_workstation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_stop_workstation_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_stop_workstation") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_stop_workstation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.StopWorkstationRequest.pb(workstations.StopWorkstationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_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 = workstations.StopWorkstationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.stop_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_stop_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.StopWorkstationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.stop_workstation(request) + + +def test_stop_workstation_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.stop_workstation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:stop" % client.transport._host, args[1]) + + +def test_stop_workstation_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.stop_workstation( + workstations.StopWorkstationRequest(), + name='name_value', + ) + + +def test_stop_workstation_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + workstations.GenerateAccessTokenRequest, + dict, +]) +def test_generate_access_token_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.GenerateAccessTokenResponse( + access_token='access_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = workstations.GenerateAccessTokenResponse.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.generate_access_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, workstations.GenerateAccessTokenResponse) + assert response.access_token == 'access_token_value' + + +def test_generate_access_token_rest_required_fields(request_type=workstations.GenerateAccessTokenRequest): + transport_class = transports.WorkstationsRestTransport + + request_init = {} + request_init["workstation"] = "" + 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()).generate_access_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["workstation"] = 'workstation_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_access_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "workstation" in jsonified_request + assert jsonified_request["workstation"] == 'workstation_value' + + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = workstations.GenerateAccessTokenResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # 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 + + pb_return_value = workstations.GenerateAccessTokenResponse.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.generate_access_token(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_generate_access_token_rest_unset_required_fields(): + transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.generate_access_token._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("workstation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_access_token_rest_interceptors(null_interceptor): + transport = transports.WorkstationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), + ) + client = WorkstationsClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "post_generate_access_token") as post, \ + mock.patch.object(transports.WorkstationsRestInterceptor, "pre_generate_access_token") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = workstations.GenerateAccessTokenRequest.pb(workstations.GenerateAccessTokenRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = workstations.GenerateAccessTokenResponse.to_json(workstations.GenerateAccessTokenResponse()) + + request = workstations.GenerateAccessTokenRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = workstations.GenerateAccessTokenResponse() + + client.generate_access_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_access_token_rest_bad_request(transport: str = 'rest', request_type=workstations.GenerateAccessTokenRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.generate_access_token(request) + + +def test_generate_access_token_rest_flattened(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = workstations.GenerateAccessTokenResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + workstation='workstation_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 = workstations.GenerateAccessTokenResponse.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.generate_access_token(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{workstation=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:generateAccessToken" % client.transport._host, args[1]) + + +def test_generate_access_token_rest_flattened_error(transport: str = 'rest'): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_access_token( + workstations.GenerateAccessTokenRequest(), + workstation='workstation_value', + ) + + +def test_generate_access_token_rest_error(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WorkstationsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WorkstationsClient( + 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 = WorkstationsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WorkstationsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WorkstationsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WorkstationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WorkstationsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.WorkstationsGrpcTransport, + transports.WorkstationsGrpcAsyncIOTransport, + transports.WorkstationsRestTransport, +]) +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 = WorkstationsClient.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 = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WorkstationsGrpcTransport, + ) + +def test_workstations_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WorkstationsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_workstations_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.workstations_v1beta.services.workstations.transports.WorkstationsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.WorkstationsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_workstation_cluster', + 'list_workstation_clusters', + 'create_workstation_cluster', + 'update_workstation_cluster', + 'delete_workstation_cluster', + 'get_workstation_config', + 'list_workstation_configs', + 'list_usable_workstation_configs', + 'create_workstation_config', + 'update_workstation_config', + 'delete_workstation_config', + 'get_workstation', + 'list_workstations', + 'list_usable_workstations', + 'create_workstation', + 'update_workstation', + 'delete_workstation', + 'start_workstation', + 'stop_workstation', + 'generate_access_token', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_workstations_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.workstations_v1beta.services.workstations.transports.WorkstationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WorkstationsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_workstations_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.workstations_v1beta.services.workstations.transports.WorkstationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WorkstationsTransport() + adc.assert_called_once() + + +def test_workstations_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) + WorkstationsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WorkstationsGrpcTransport, + transports.WorkstationsGrpcAsyncIOTransport, + ], +) +def test_workstations_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WorkstationsGrpcTransport, + transports.WorkstationsGrpcAsyncIOTransport, + transports.WorkstationsRestTransport, + ], +) +def test_workstations_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.WorkstationsGrpcTransport, grpc_helpers), + (transports.WorkstationsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_workstations_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( + "workstations.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="workstations.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) +def test_workstations_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_workstations_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.WorkstationsRestTransport ( + 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_workstations_rest_lro_client(): + client = WorkstationsClient( + 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_workstations_host_no_port(transport_name): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='workstations.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'workstations.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://workstations.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_workstations_host_with_port(transport_name): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='workstations.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'workstations.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://workstations.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_workstations_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = WorkstationsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = WorkstationsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_workstation_cluster._session + session2 = client2.transport.get_workstation_cluster._session + assert session1 != session2 + session1 = client1.transport.list_workstation_clusters._session + session2 = client2.transport.list_workstation_clusters._session + assert session1 != session2 + session1 = client1.transport.create_workstation_cluster._session + session2 = client2.transport.create_workstation_cluster._session + assert session1 != session2 + session1 = client1.transport.update_workstation_cluster._session + session2 = client2.transport.update_workstation_cluster._session + assert session1 != session2 + session1 = client1.transport.delete_workstation_cluster._session + session2 = client2.transport.delete_workstation_cluster._session + assert session1 != session2 + session1 = client1.transport.get_workstation_config._session + session2 = client2.transport.get_workstation_config._session + assert session1 != session2 + session1 = client1.transport.list_workstation_configs._session + session2 = client2.transport.list_workstation_configs._session + assert session1 != session2 + session1 = client1.transport.list_usable_workstation_configs._session + session2 = client2.transport.list_usable_workstation_configs._session + assert session1 != session2 + session1 = client1.transport.create_workstation_config._session + session2 = client2.transport.create_workstation_config._session + assert session1 != session2 + session1 = client1.transport.update_workstation_config._session + session2 = client2.transport.update_workstation_config._session + assert session1 != session2 + session1 = client1.transport.delete_workstation_config._session + session2 = client2.transport.delete_workstation_config._session + assert session1 != session2 + session1 = client1.transport.get_workstation._session + session2 = client2.transport.get_workstation._session + assert session1 != session2 + session1 = client1.transport.list_workstations._session + session2 = client2.transport.list_workstations._session + assert session1 != session2 + session1 = client1.transport.list_usable_workstations._session + session2 = client2.transport.list_usable_workstations._session + assert session1 != session2 + session1 = client1.transport.create_workstation._session + session2 = client2.transport.create_workstation._session + assert session1 != session2 + session1 = client1.transport.update_workstation._session + session2 = client2.transport.update_workstation._session + assert session1 != session2 + session1 = client1.transport.delete_workstation._session + session2 = client2.transport.delete_workstation._session + assert session1 != session2 + session1 = client1.transport.start_workstation._session + session2 = client2.transport.start_workstation._session + assert session1 != session2 + session1 = client1.transport.stop_workstation._session + session2 = client2.transport.stop_workstation._session + assert session1 != session2 + session1 = client1.transport.generate_access_token._session + session2 = client2.transport.generate_access_token._session + assert session1 != session2 +def test_workstations_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WorkstationsGrpcTransport( + 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_workstations_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WorkstationsGrpcAsyncIOTransport( + 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.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) +def test_workstations_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.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) +def test_workstations_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_workstations_grpc_lro_client(): + client = WorkstationsClient( + 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_workstations_grpc_lro_async_client(): + client = WorkstationsAsyncClient( + 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_workstation_path(): + project = "squid" + location = "clam" + workstation_cluster = "whelk" + workstation_config = "octopus" + workstation = "oyster" + expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}/workstations/{workstation}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, workstation=workstation, ) + actual = WorkstationsClient.workstation_path(project, location, workstation_cluster, workstation_config, workstation) + assert expected == actual + + +def test_parse_workstation_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "workstation_cluster": "mussel", + "workstation_config": "winkle", + "workstation": "nautilus", + } + path = WorkstationsClient.workstation_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_workstation_path(path) + assert expected == actual + +def test_workstation_cluster_path(): + project = "scallop" + location = "abalone" + workstation_cluster = "squid" + expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}".format(project=project, location=location, workstation_cluster=workstation_cluster, ) + actual = WorkstationsClient.workstation_cluster_path(project, location, workstation_cluster) + assert expected == actual + + +def test_parse_workstation_cluster_path(): + expected = { + "project": "clam", + "location": "whelk", + "workstation_cluster": "octopus", + } + path = WorkstationsClient.workstation_cluster_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_workstation_cluster_path(path) + assert expected == actual + +def test_workstation_config_path(): + project = "oyster" + location = "nudibranch" + workstation_cluster = "cuttlefish" + workstation_config = "mussel" + expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, ) + actual = WorkstationsClient.workstation_config_path(project, location, workstation_cluster, workstation_config) + assert expected == actual + + +def test_parse_workstation_config_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "workstation_cluster": "scallop", + "workstation_config": "abalone", + } + path = WorkstationsClient.workstation_config_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_workstation_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = WorkstationsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = WorkstationsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = WorkstationsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = WorkstationsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = WorkstationsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = WorkstationsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = WorkstationsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = WorkstationsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = WorkstationsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = WorkstationsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = WorkstationsClient.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.WorkstationsTransport, '_prep_wrapped_messages') as prep: + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.WorkstationsTransport, '_prep_wrapped_messages') as prep: + transport_class = WorkstationsClient.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 = WorkstationsAsyncClient( + 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_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc"): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_delete_operation_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc"): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = WorkstationsAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = WorkstationsAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = WorkstationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = WorkstationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = WorkstationsAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = WorkstationsClient( + 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 = WorkstationsClient( + 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", [ + (WorkstationsClient, transports.WorkstationsGrpcTransport), + (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport), +]) +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 3395355596ba7addc042514a8a6e334e2cef0b7f Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 24 Aug 2023 20:57:03 +0000 Subject: [PATCH 4/4] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../google-cloud-workstations/v1/.coveragerc | 13 - .../google-cloud-workstations/v1/.flake8 | 33 - .../google-cloud-workstations/v1/MANIFEST.in | 2 - .../google-cloud-workstations/v1/README.rst | 49 - .../google-cloud-workstations/v1/docs/conf.py | 376 - .../v1/docs/index.rst | 7 - .../v1/docs/workstations_v1/services.rst | 6 - .../v1/docs/workstations_v1/types.rst | 6 - .../v1/docs/workstations_v1/workstations.rst | 10 - .../v1/google/cloud/workstations/__init__.py | 87 - .../cloud/workstations/gapic_version.py | 16 - .../v1/google/cloud/workstations/py.typed | 2 - .../google/cloud/workstations_v1/__init__.py | 88 - .../cloud/workstations_v1/gapic_metadata.json | 328 - .../cloud/workstations_v1/gapic_version.py | 16 - .../v1/google/cloud/workstations_v1/py.typed | 2 - .../workstations_v1/services/__init__.py | 15 - .../services/workstations/__init__.py | 22 - .../services/workstations/async_client.py | 3093 ---- .../services/workstations/client.py | 3259 ---- .../services/workstations/pagers.py | 623 - .../workstations/transports/__init__.py | 38 - .../services/workstations/transports/base.py | 545 - .../services/workstations/transports/grpc.py | 943 -- .../workstations/transports/grpc_asyncio.py | 942 -- .../services/workstations/transports/rest.py | 3177 ---- .../cloud/workstations_v1/types/__init__.py | 80 - .../workstations_v1/types/workstations.py | 1722 -- .../google-cloud-workstations/v1/mypy.ini | 3 - .../google-cloud-workstations/v1/noxfile.py | 184 - ...metadata_google.cloud.workstations.v1.json | 3307 ---- ...d_workstations_create_workstation_async.py | 57 - ...ations_create_workstation_cluster_async.py | 57 - ...tations_create_workstation_cluster_sync.py | 57 - ...tations_create_workstation_config_async.py | 57 - ...stations_create_workstation_config_sync.py | 57 - ...ed_workstations_create_workstation_sync.py | 57 - ...d_workstations_delete_workstation_async.py | 56 - ...ations_delete_workstation_cluster_async.py | 56 - ...tations_delete_workstation_cluster_sync.py | 56 - ...tations_delete_workstation_config_async.py | 56 - ...stations_delete_workstation_config_sync.py | 56 - ...ed_workstations_delete_workstation_sync.py | 56 - ...orkstations_generate_access_token_async.py | 52 - ...workstations_generate_access_token_sync.py | 52 - ...ated_workstations_get_workstation_async.py | 52 - ...kstations_get_workstation_cluster_async.py | 52 - ...rkstations_get_workstation_cluster_sync.py | 52 - ...rkstations_get_workstation_config_async.py | 52 - ...orkstations_get_workstation_config_sync.py | 52 - ...rated_workstations_get_workstation_sync.py | 52 - ...s_list_usable_workstation_configs_async.py | 53 - ...ns_list_usable_workstation_configs_sync.py | 53 - ...stations_list_usable_workstations_async.py | 53 - ...kstations_list_usable_workstations_sync.py | 53 - ...tations_list_workstation_clusters_async.py | 53 - ...stations_list_workstation_clusters_sync.py | 53 - ...stations_list_workstation_configs_async.py | 53 - ...kstations_list_workstation_configs_sync.py | 53 - ...ed_workstations_list_workstations_async.py | 53 - ...ted_workstations_list_workstations_sync.py | 53 - ...ed_workstations_start_workstation_async.py | 56 - ...ted_workstations_start_workstation_sync.py | 56 - ...ted_workstations_stop_workstation_async.py | 56 - ...ated_workstations_stop_workstation_sync.py | 56 - ...d_workstations_update_workstation_async.py | 55 - ...ations_update_workstation_cluster_async.py | 55 - ...tations_update_workstation_cluster_sync.py | 55 - ...tations_update_workstation_config_async.py | 55 - ...stations_update_workstation_config_sync.py | 55 - ...ed_workstations_update_workstation_sync.py | 55 - .../scripts/fixup_workstations_v1_keywords.py | 195 - .../google-cloud-workstations/v1/setup.py | 91 - .../v1/testing/constraints-3.10.txt | 7 - .../v1/testing/constraints-3.11.txt | 7 - .../v1/testing/constraints-3.12.txt | 7 - .../v1/testing/constraints-3.7.txt | 10 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - .../v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/workstations_v1/__init__.py | 16 - .../workstations_v1/test_workstations.py | 13498 --------------- .../v1beta/.coveragerc | 13 - .../google-cloud-workstations/v1beta/.flake8 | 33 - .../v1beta/MANIFEST.in | 2 - .../v1beta/README.rst | 49 - .../v1beta/docs/conf.py | 376 - .../v1beta/docs/index.rst | 7 - .../docs/workstations_v1beta/services.rst | 6 - .../v1beta/docs/workstations_v1beta/types.rst | 6 - .../docs/workstations_v1beta/workstations.rst | 10 - .../google/cloud/workstations/__init__.py | 87 - .../cloud/workstations/gapic_version.py | 16 - .../v1beta/google/cloud/workstations/py.typed | 2 - .../cloud/workstations_v1beta/__init__.py | 88 - .../workstations_v1beta/gapic_metadata.json | 328 - .../workstations_v1beta/gapic_version.py | 16 - .../google/cloud/workstations_v1beta/py.typed | 2 - .../workstations_v1beta/services/__init__.py | 15 - .../services/workstations/__init__.py | 22 - .../services/workstations/async_client.py | 3093 ---- .../services/workstations/client.py | 3259 ---- .../services/workstations/pagers.py | 623 - .../workstations/transports/__init__.py | 38 - .../services/workstations/transports/base.py | 545 - .../services/workstations/transports/grpc.py | 943 -- .../workstations/transports/grpc_asyncio.py | 942 -- .../services/workstations/transports/rest.py | 3177 ---- .../workstations_v1beta/types/__init__.py | 80 - .../workstations_v1beta/types/workstations.py | 1793 -- .../google-cloud-workstations/v1beta/mypy.ini | 3 - .../v1beta/noxfile.py | 184 - ...data_google.cloud.workstations.v1beta.json | 3307 ---- ...d_workstations_create_workstation_async.py | 57 - ...ations_create_workstation_cluster_async.py | 57 - ...tations_create_workstation_cluster_sync.py | 57 - ...tations_create_workstation_config_async.py | 57 - ...stations_create_workstation_config_sync.py | 57 - ...ed_workstations_create_workstation_sync.py | 57 - ...d_workstations_delete_workstation_async.py | 56 - ...ations_delete_workstation_cluster_async.py | 56 - ...tations_delete_workstation_cluster_sync.py | 56 - ...tations_delete_workstation_config_async.py | 56 - ...stations_delete_workstation_config_sync.py | 56 - ...ed_workstations_delete_workstation_sync.py | 56 - ...orkstations_generate_access_token_async.py | 52 - ...workstations_generate_access_token_sync.py | 52 - ...ated_workstations_get_workstation_async.py | 52 - ...kstations_get_workstation_cluster_async.py | 52 - ...rkstations_get_workstation_cluster_sync.py | 52 - ...rkstations_get_workstation_config_async.py | 52 - ...orkstations_get_workstation_config_sync.py | 52 - ...rated_workstations_get_workstation_sync.py | 52 - ...s_list_usable_workstation_configs_async.py | 53 - ...ns_list_usable_workstation_configs_sync.py | 53 - ...stations_list_usable_workstations_async.py | 53 - ...kstations_list_usable_workstations_sync.py | 53 - ...tations_list_workstation_clusters_async.py | 53 - ...stations_list_workstation_clusters_sync.py | 53 - ...stations_list_workstation_configs_async.py | 53 - ...kstations_list_workstation_configs_sync.py | 53 - ...ed_workstations_list_workstations_async.py | 53 - ...ted_workstations_list_workstations_sync.py | 53 - ...ed_workstations_start_workstation_async.py | 56 - ...ted_workstations_start_workstation_sync.py | 56 - ...ted_workstations_stop_workstation_async.py | 56 - ...ated_workstations_stop_workstation_sync.py | 56 - ...d_workstations_update_workstation_async.py | 55 - ...ations_update_workstation_cluster_async.py | 55 - ...tations_update_workstation_cluster_sync.py | 55 - ...tations_update_workstation_config_async.py | 55 - ...stations_update_workstation_config_sync.py | 55 - ...ed_workstations_update_workstation_sync.py | 55 - .../fixup_workstations_v1beta_keywords.py | 195 - .../google-cloud-workstations/v1beta/setup.py | 91 - .../v1beta/testing/constraints-3.10.txt | 7 - .../v1beta/testing/constraints-3.11.txt | 7 - .../v1beta/testing/constraints-3.12.txt | 7 - .../v1beta/testing/constraints-3.7.txt | 10 - .../v1beta/testing/constraints-3.8.txt | 7 - .../v1beta/testing/constraints-3.9.txt | 7 - .../v1beta/tests/__init__.py | 16 - .../v1beta/tests/unit/__init__.py | 16 - .../v1beta/tests/unit/gapic/__init__.py | 16 - .../gapic/workstations_v1beta/__init__.py | 16 - .../workstations_v1beta/test_workstations.py | 13504 ---------------- packages/google-cloud-workstations/.flake8 | 2 +- .../CONTRIBUTING.rst | 2 +- .../google-cloud-workstations/MANIFEST.in | 2 +- packages/google-cloud-workstations/README.rst | 47 +- .../google-cloud-workstations/docs/conf.py | 2 +- .../google-cloud-workstations/docs/index.rst | 2 +- packages/google-cloud-workstations/noxfile.py | 2 +- .../scripts/decrypt-secrets.sh | 2 +- 176 files changed, 31 insertions(+), 70237 deletions(-) delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/README.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/services.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/types.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/workstations.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/py.typed delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/py.typed delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/async_client.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/client.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/pagers.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/workstations.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/scripts/fixup_workstations_v1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/setup.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/test_workstations.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/.flake8 delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/README.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/services.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/types.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/workstations.rst delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/py.typed delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/py.typed delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/async_client.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/client.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/pagers.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/workstations.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_async.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_sync.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/scripts/fixup_workstations_v1beta_keywords.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/setup.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/test_workstations.py diff --git a/owl-bot-staging/google-cloud-workstations/v1/.coveragerc b/owl-bot-staging/google-cloud-workstations/v1/.coveragerc deleted file mode 100644 index ee1a17c3e2ca..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/workstations/__init__.py - google/cloud/workstations/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-cloud-workstations/v1/.flake8 b/owl-bot-staging/google-cloud-workstations/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-cloud-workstations/v1/MANIFEST.in b/owl-bot-staging/google-cloud-workstations/v1/MANIFEST.in deleted file mode 100644 index 81d49b157276..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/workstations *.py -recursive-include google/cloud/workstations_v1 *.py diff --git a/owl-bot-staging/google-cloud-workstations/v1/README.rst b/owl-bot-staging/google-cloud-workstations/v1/README.rst deleted file mode 100644 index 48a711be018f..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Workstations 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 Workstations API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-workstations/v1/docs/conf.py b/owl-bot-staging/google-cloud-workstations/v1/docs/conf.py deleted file mode 100644 index 06f3a6eac397..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-workstations 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-workstations" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = 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-workstations-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-workstations.tex", - u"google-cloud-workstations 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-workstations", - u"Google Cloud Workstations 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-workstations", - u"google-cloud-workstations Documentation", - author, - "google-cloud-workstations", - "GAPIC library for Google Cloud Workstations API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-workstations/v1/docs/index.rst b/owl-bot-staging/google-cloud-workstations/v1/docs/index.rst deleted file mode 100644 index d037fecd058a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - workstations_v1/services - workstations_v1/types diff --git a/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/services.rst b/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/services.rst deleted file mode 100644 index 4d34f8795a80..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Workstations v1 API -============================================= -.. toctree:: - :maxdepth: 2 - - workstations diff --git a/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/types.rst b/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/types.rst deleted file mode 100644 index f2d1f8aae76b..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Workstations v1 API -========================================== - -.. automodule:: google.cloud.workstations_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/workstations.rst b/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/workstations.rst deleted file mode 100644 index 1a3ded4d683d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/docs/workstations_v1/workstations.rst +++ /dev/null @@ -1,10 +0,0 @@ -Workstations ------------------------------- - -.. automodule:: google.cloud.workstations_v1.services.workstations - :members: - :inherited-members: - -.. automodule:: google.cloud.workstations_v1.services.workstations.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/__init__.py deleted file mode 100644 index 1528fb82f971..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/__init__.py +++ /dev/null @@ -1,87 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.workstations import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.workstations_v1.services.workstations.client import WorkstationsClient -from google.cloud.workstations_v1.services.workstations.async_client import WorkstationsAsyncClient - -from google.cloud.workstations_v1.types.workstations import CreateWorkstationClusterRequest -from google.cloud.workstations_v1.types.workstations import CreateWorkstationConfigRequest -from google.cloud.workstations_v1.types.workstations import CreateWorkstationRequest -from google.cloud.workstations_v1.types.workstations import DeleteWorkstationClusterRequest -from google.cloud.workstations_v1.types.workstations import DeleteWorkstationConfigRequest -from google.cloud.workstations_v1.types.workstations import DeleteWorkstationRequest -from google.cloud.workstations_v1.types.workstations import GenerateAccessTokenRequest -from google.cloud.workstations_v1.types.workstations import GenerateAccessTokenResponse -from google.cloud.workstations_v1.types.workstations import GetWorkstationClusterRequest -from google.cloud.workstations_v1.types.workstations import GetWorkstationConfigRequest -from google.cloud.workstations_v1.types.workstations import GetWorkstationRequest -from google.cloud.workstations_v1.types.workstations import ListUsableWorkstationConfigsRequest -from google.cloud.workstations_v1.types.workstations import ListUsableWorkstationConfigsResponse -from google.cloud.workstations_v1.types.workstations import ListUsableWorkstationsRequest -from google.cloud.workstations_v1.types.workstations import ListUsableWorkstationsResponse -from google.cloud.workstations_v1.types.workstations import ListWorkstationClustersRequest -from google.cloud.workstations_v1.types.workstations import ListWorkstationClustersResponse -from google.cloud.workstations_v1.types.workstations import ListWorkstationConfigsRequest -from google.cloud.workstations_v1.types.workstations import ListWorkstationConfigsResponse -from google.cloud.workstations_v1.types.workstations import ListWorkstationsRequest -from google.cloud.workstations_v1.types.workstations import ListWorkstationsResponse -from google.cloud.workstations_v1.types.workstations import OperationMetadata -from google.cloud.workstations_v1.types.workstations import StartWorkstationRequest -from google.cloud.workstations_v1.types.workstations import StopWorkstationRequest -from google.cloud.workstations_v1.types.workstations import UpdateWorkstationClusterRequest -from google.cloud.workstations_v1.types.workstations import UpdateWorkstationConfigRequest -from google.cloud.workstations_v1.types.workstations import UpdateWorkstationRequest -from google.cloud.workstations_v1.types.workstations import Workstation -from google.cloud.workstations_v1.types.workstations import WorkstationCluster -from google.cloud.workstations_v1.types.workstations import WorkstationConfig - -__all__ = ('WorkstationsClient', - 'WorkstationsAsyncClient', - 'CreateWorkstationClusterRequest', - 'CreateWorkstationConfigRequest', - 'CreateWorkstationRequest', - 'DeleteWorkstationClusterRequest', - 'DeleteWorkstationConfigRequest', - 'DeleteWorkstationRequest', - 'GenerateAccessTokenRequest', - 'GenerateAccessTokenResponse', - 'GetWorkstationClusterRequest', - 'GetWorkstationConfigRequest', - 'GetWorkstationRequest', - 'ListUsableWorkstationConfigsRequest', - 'ListUsableWorkstationConfigsResponse', - 'ListUsableWorkstationsRequest', - 'ListUsableWorkstationsResponse', - 'ListWorkstationClustersRequest', - 'ListWorkstationClustersResponse', - 'ListWorkstationConfigsRequest', - 'ListWorkstationConfigsResponse', - 'ListWorkstationsRequest', - 'ListWorkstationsResponse', - 'OperationMetadata', - 'StartWorkstationRequest', - 'StopWorkstationRequest', - 'UpdateWorkstationClusterRequest', - 'UpdateWorkstationConfigRequest', - 'UpdateWorkstationRequest', - 'Workstation', - 'WorkstationCluster', - 'WorkstationConfig', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/gapic_version.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/gapic_version.py deleted file mode 100644 index 360a0d13ebdd..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/py.typed b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/py.typed deleted file mode 100644 index 04170223dff9..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-workstations package uses inline types. diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/__init__.py deleted file mode 100644 index 406625485e84..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/__init__.py +++ /dev/null @@ -1,88 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.workstations_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.workstations import WorkstationsClient -from .services.workstations import WorkstationsAsyncClient - -from .types.workstations import CreateWorkstationClusterRequest -from .types.workstations import CreateWorkstationConfigRequest -from .types.workstations import CreateWorkstationRequest -from .types.workstations import DeleteWorkstationClusterRequest -from .types.workstations import DeleteWorkstationConfigRequest -from .types.workstations import DeleteWorkstationRequest -from .types.workstations import GenerateAccessTokenRequest -from .types.workstations import GenerateAccessTokenResponse -from .types.workstations import GetWorkstationClusterRequest -from .types.workstations import GetWorkstationConfigRequest -from .types.workstations import GetWorkstationRequest -from .types.workstations import ListUsableWorkstationConfigsRequest -from .types.workstations import ListUsableWorkstationConfigsResponse -from .types.workstations import ListUsableWorkstationsRequest -from .types.workstations import ListUsableWorkstationsResponse -from .types.workstations import ListWorkstationClustersRequest -from .types.workstations import ListWorkstationClustersResponse -from .types.workstations import ListWorkstationConfigsRequest -from .types.workstations import ListWorkstationConfigsResponse -from .types.workstations import ListWorkstationsRequest -from .types.workstations import ListWorkstationsResponse -from .types.workstations import OperationMetadata -from .types.workstations import StartWorkstationRequest -from .types.workstations import StopWorkstationRequest -from .types.workstations import UpdateWorkstationClusterRequest -from .types.workstations import UpdateWorkstationConfigRequest -from .types.workstations import UpdateWorkstationRequest -from .types.workstations import Workstation -from .types.workstations import WorkstationCluster -from .types.workstations import WorkstationConfig - -__all__ = ( - 'WorkstationsAsyncClient', -'CreateWorkstationClusterRequest', -'CreateWorkstationConfigRequest', -'CreateWorkstationRequest', -'DeleteWorkstationClusterRequest', -'DeleteWorkstationConfigRequest', -'DeleteWorkstationRequest', -'GenerateAccessTokenRequest', -'GenerateAccessTokenResponse', -'GetWorkstationClusterRequest', -'GetWorkstationConfigRequest', -'GetWorkstationRequest', -'ListUsableWorkstationConfigsRequest', -'ListUsableWorkstationConfigsResponse', -'ListUsableWorkstationsRequest', -'ListUsableWorkstationsResponse', -'ListWorkstationClustersRequest', -'ListWorkstationClustersResponse', -'ListWorkstationConfigsRequest', -'ListWorkstationConfigsResponse', -'ListWorkstationsRequest', -'ListWorkstationsResponse', -'OperationMetadata', -'StartWorkstationRequest', -'StopWorkstationRequest', -'UpdateWorkstationClusterRequest', -'UpdateWorkstationConfigRequest', -'UpdateWorkstationRequest', -'Workstation', -'WorkstationCluster', -'WorkstationConfig', -'WorkstationsClient', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_metadata.json deleted file mode 100644 index 27a21c6d848b..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_metadata.json +++ /dev/null @@ -1,328 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.workstations_v1", - "protoPackage": "google.cloud.workstations.v1", - "schema": "1.0", - "services": { - "Workstations": { - "clients": { - "grpc": { - "libraryClient": "WorkstationsClient", - "rpcs": { - "CreateWorkstation": { - "methods": [ - "create_workstation" - ] - }, - "CreateWorkstationCluster": { - "methods": [ - "create_workstation_cluster" - ] - }, - "CreateWorkstationConfig": { - "methods": [ - "create_workstation_config" - ] - }, - "DeleteWorkstation": { - "methods": [ - "delete_workstation" - ] - }, - "DeleteWorkstationCluster": { - "methods": [ - "delete_workstation_cluster" - ] - }, - "DeleteWorkstationConfig": { - "methods": [ - "delete_workstation_config" - ] - }, - "GenerateAccessToken": { - "methods": [ - "generate_access_token" - ] - }, - "GetWorkstation": { - "methods": [ - "get_workstation" - ] - }, - "GetWorkstationCluster": { - "methods": [ - "get_workstation_cluster" - ] - }, - "GetWorkstationConfig": { - "methods": [ - "get_workstation_config" - ] - }, - "ListUsableWorkstationConfigs": { - "methods": [ - "list_usable_workstation_configs" - ] - }, - "ListUsableWorkstations": { - "methods": [ - "list_usable_workstations" - ] - }, - "ListWorkstationClusters": { - "methods": [ - "list_workstation_clusters" - ] - }, - "ListWorkstationConfigs": { - "methods": [ - "list_workstation_configs" - ] - }, - "ListWorkstations": { - "methods": [ - "list_workstations" - ] - }, - "StartWorkstation": { - "methods": [ - "start_workstation" - ] - }, - "StopWorkstation": { - "methods": [ - "stop_workstation" - ] - }, - "UpdateWorkstation": { - "methods": [ - "update_workstation" - ] - }, - "UpdateWorkstationCluster": { - "methods": [ - "update_workstation_cluster" - ] - }, - "UpdateWorkstationConfig": { - "methods": [ - "update_workstation_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "WorkstationsAsyncClient", - "rpcs": { - "CreateWorkstation": { - "methods": [ - "create_workstation" - ] - }, - "CreateWorkstationCluster": { - "methods": [ - "create_workstation_cluster" - ] - }, - "CreateWorkstationConfig": { - "methods": [ - "create_workstation_config" - ] - }, - "DeleteWorkstation": { - "methods": [ - "delete_workstation" - ] - }, - "DeleteWorkstationCluster": { - "methods": [ - "delete_workstation_cluster" - ] - }, - "DeleteWorkstationConfig": { - "methods": [ - "delete_workstation_config" - ] - }, - "GenerateAccessToken": { - "methods": [ - "generate_access_token" - ] - }, - "GetWorkstation": { - "methods": [ - "get_workstation" - ] - }, - "GetWorkstationCluster": { - "methods": [ - "get_workstation_cluster" - ] - }, - "GetWorkstationConfig": { - "methods": [ - "get_workstation_config" - ] - }, - "ListUsableWorkstationConfigs": { - "methods": [ - "list_usable_workstation_configs" - ] - }, - "ListUsableWorkstations": { - "methods": [ - "list_usable_workstations" - ] - }, - "ListWorkstationClusters": { - "methods": [ - "list_workstation_clusters" - ] - }, - "ListWorkstationConfigs": { - "methods": [ - "list_workstation_configs" - ] - }, - "ListWorkstations": { - "methods": [ - "list_workstations" - ] - }, - "StartWorkstation": { - "methods": [ - "start_workstation" - ] - }, - "StopWorkstation": { - "methods": [ - "stop_workstation" - ] - }, - "UpdateWorkstation": { - "methods": [ - "update_workstation" - ] - }, - "UpdateWorkstationCluster": { - "methods": [ - "update_workstation_cluster" - ] - }, - "UpdateWorkstationConfig": { - "methods": [ - "update_workstation_config" - ] - } - } - }, - "rest": { - "libraryClient": "WorkstationsClient", - "rpcs": { - "CreateWorkstation": { - "methods": [ - "create_workstation" - ] - }, - "CreateWorkstationCluster": { - "methods": [ - "create_workstation_cluster" - ] - }, - "CreateWorkstationConfig": { - "methods": [ - "create_workstation_config" - ] - }, - "DeleteWorkstation": { - "methods": [ - "delete_workstation" - ] - }, - "DeleteWorkstationCluster": { - "methods": [ - "delete_workstation_cluster" - ] - }, - "DeleteWorkstationConfig": { - "methods": [ - "delete_workstation_config" - ] - }, - "GenerateAccessToken": { - "methods": [ - "generate_access_token" - ] - }, - "GetWorkstation": { - "methods": [ - "get_workstation" - ] - }, - "GetWorkstationCluster": { - "methods": [ - "get_workstation_cluster" - ] - }, - "GetWorkstationConfig": { - "methods": [ - "get_workstation_config" - ] - }, - "ListUsableWorkstationConfigs": { - "methods": [ - "list_usable_workstation_configs" - ] - }, - "ListUsableWorkstations": { - "methods": [ - "list_usable_workstations" - ] - }, - "ListWorkstationClusters": { - "methods": [ - "list_workstation_clusters" - ] - }, - "ListWorkstationConfigs": { - "methods": [ - "list_workstation_configs" - ] - }, - "ListWorkstations": { - "methods": [ - "list_workstations" - ] - }, - "StartWorkstation": { - "methods": [ - "start_workstation" - ] - }, - "StopWorkstation": { - "methods": [ - "stop_workstation" - ] - }, - "UpdateWorkstation": { - "methods": [ - "update_workstation" - ] - }, - "UpdateWorkstationCluster": { - "methods": [ - "update_workstation_cluster" - ] - }, - "UpdateWorkstationConfig": { - "methods": [ - "update_workstation_config" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_version.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_version.py deleted file mode 100644 index 360a0d13ebdd..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/py.typed b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/py.typed deleted file mode 100644 index 04170223dff9..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-workstations package uses inline types. diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/__init__.py deleted file mode 100644 index 89a37dc92c5a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/__init__.py deleted file mode 100644 index 0d8e475505ba..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 WorkstationsClient -from .async_client import WorkstationsAsyncClient - -__all__ = ( - 'WorkstationsClient', - 'WorkstationsAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/async_client.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/async_client.py deleted file mode 100644 index 2eb4b2d0b046..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/async_client.py +++ /dev/null @@ -1,3093 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.workstations_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1.services.workstations import pagers -from google.cloud.workstations_v1.types import workstations -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 -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import WorkstationsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import WorkstationsGrpcAsyncIOTransport -from .client import WorkstationsClient - - -class WorkstationsAsyncClient: - """Service for interacting with Cloud Workstations.""" - - _client: WorkstationsClient - - DEFAULT_ENDPOINT = WorkstationsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = WorkstationsClient.DEFAULT_MTLS_ENDPOINT - - workstation_path = staticmethod(WorkstationsClient.workstation_path) - parse_workstation_path = staticmethod(WorkstationsClient.parse_workstation_path) - workstation_cluster_path = staticmethod(WorkstationsClient.workstation_cluster_path) - parse_workstation_cluster_path = staticmethod(WorkstationsClient.parse_workstation_cluster_path) - workstation_config_path = staticmethod(WorkstationsClient.workstation_config_path) - parse_workstation_config_path = staticmethod(WorkstationsClient.parse_workstation_config_path) - common_billing_account_path = staticmethod(WorkstationsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(WorkstationsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(WorkstationsClient.common_folder_path) - parse_common_folder_path = staticmethod(WorkstationsClient.parse_common_folder_path) - common_organization_path = staticmethod(WorkstationsClient.common_organization_path) - parse_common_organization_path = staticmethod(WorkstationsClient.parse_common_organization_path) - common_project_path = staticmethod(WorkstationsClient.common_project_path) - parse_common_project_path = staticmethod(WorkstationsClient.parse_common_project_path) - common_location_path = staticmethod(WorkstationsClient.common_location_path) - parse_common_location_path = staticmethod(WorkstationsClient.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: - WorkstationsAsyncClient: The constructed client. - """ - return WorkstationsClient.from_service_account_info.__func__(WorkstationsAsyncClient, 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: - WorkstationsAsyncClient: The constructed client. - """ - return WorkstationsClient.from_service_account_file.__func__(WorkstationsAsyncClient, 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 WorkstationsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> WorkstationsTransport: - """Returns the transport used by the client instance. - - Returns: - WorkstationsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(WorkstationsClient).get_transport_class, type(WorkstationsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, WorkstationsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the workstations 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, ~.WorkstationsTransport]): 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 = WorkstationsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_workstation_cluster(self, - request: Optional[Union[workstations.GetWorkstationClusterRequest, 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]] = (), - ) -> workstations.WorkstationCluster: - r"""Returns the requested workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_get_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation_cluster(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.GetWorkstationClusterRequest, dict]]): - The request object. Request message for - GetWorkstationCluster. - name (:class:`str`): - Required. Name of the requested - resource. - - 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.workstations_v1.types.WorkstationCluster: - A grouping of workstation - configurations and the associated - workstations in that region. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = workstations.GetWorkstationClusterRequest(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_workstation_cluster, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_workstation_clusters(self, - request: Optional[Union[workstations.ListWorkstationClustersRequest, 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.ListWorkstationClustersAsyncPager: - r"""Returns all workstation clusters in the specified - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_list_workstation_clusters(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_clusters(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.ListWorkstationClustersRequest, dict]]): - The request object. Request message for - ListWorkstationClusters. - parent (:class:`str`): - Required. Parent resource name. - 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.workstations_v1.services.workstations.pagers.ListWorkstationClustersAsyncPager: - Response message for - ListWorkstationClusters. - 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 = workstations.ListWorkstationClustersRequest(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_workstation_clusters, - default_retry=retries.Retry( -initial=1.0,maximum=10.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(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListWorkstationClustersAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_workstation_cluster(self, - request: Optional[Union[workstations.CreateWorkstationClusterRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation_cluster: Optional[workstations.WorkstationCluster] = None, - workstation_cluster_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_create_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationClusterRequest( - parent="parent_value", - workstation_cluster_id="workstation_cluster_id_value", - ) - - # Make the request - operation = client.create_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.CreateWorkstationClusterRequest, dict]]): - The request object. Message for creating a - CreateWorkstationCluster. - parent (:class:`str`): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_cluster (:class:`google.cloud.workstations_v1.types.WorkstationCluster`): - Required. Workstation cluster to - create. - - This corresponds to the ``workstation_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_cluster_id (:class:`str`): - Required. ID to use for the - workstation cluster. - - This corresponds to the ``workstation_cluster_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.workstations_v1.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations - in that region. - - """ - # Create or coerce a protobuf request object. - # Quick 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, workstation_cluster, workstation_cluster_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = workstations.CreateWorkstationClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation_cluster is not None: - request.workstation_cluster = workstation_cluster - if workstation_cluster_id is not None: - request.workstation_cluster_id = workstation_cluster_id - - # 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_workstation_cluster, - 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(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_workstation_cluster(self, - request: Optional[Union[workstations.UpdateWorkstationClusterRequest, dict]] = None, - *, - workstation_cluster: Optional[workstations.WorkstationCluster] = 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 an existing workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_update_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationClusterRequest( - ) - - # Make the request - operation = client.update_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.UpdateWorkstationClusterRequest, dict]]): - The request object. Request message for - UpdateWorkstationCluster. - workstation_cluster (:class:`google.cloud.workstations_v1.types.WorkstationCluster`): - Required. Workstation cluster to - update. - - This corresponds to the ``workstation_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Mask that specifies which - fields in the workstation cluster should - 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.workstations_v1.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations - in that region. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation_cluster, 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 = workstations.UpdateWorkstationClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation_cluster is not None: - request.workstation_cluster = workstation_cluster - 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_workstation_cluster, - 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(( - ("workstation_cluster.name", request.workstation_cluster.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, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_workstation_cluster(self, - request: Optional[Union[workstations.DeleteWorkstationClusterRequest, 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 the specified workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_delete_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.DeleteWorkstationClusterRequest, dict]]): - The request object. Message for deleting a workstation - cluster. - name (:class:`str`): - Required. Name of the workstation - cluster to delete. - - 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.workstations_v1.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations - in that region. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = workstations.DeleteWorkstationClusterRequest(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_workstation_cluster, - 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, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_workstation_config(self, - request: Optional[Union[workstations.GetWorkstationConfigRequest, 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]] = (), - ) -> workstations.WorkstationConfig: - r"""Returns the requested workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_get_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.GetWorkstationConfigRequest, dict]]): - The request object. Request message for - GetWorkstationConfig. - name (:class:`str`): - Required. Name of the requested - resource. - - 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.workstations_v1.types.WorkstationConfig: - A set of configuration options - describing how a workstation will be - run. Workstation configurations are - intended to be shared across multiple - workstations. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = workstations.GetWorkstationConfigRequest(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_workstation_config, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_workstation_configs(self, - request: Optional[Union[workstations.ListWorkstationConfigsRequest, 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.ListWorkstationConfigsAsyncPager: - r"""Returns all workstation configurations in the - specified cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_list_workstation_configs(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.ListWorkstationConfigsRequest, dict]]): - The request object. Request message for - ListWorkstationConfigs. - parent (:class:`str`): - Required. Parent resource name. - 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.workstations_v1.services.workstations.pagers.ListWorkstationConfigsAsyncPager: - Response message for - ListWorkstationConfigs. - 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 = workstations.ListWorkstationConfigsRequest(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_workstation_configs, - default_retry=retries.Retry( -initial=1.0,maximum=10.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(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListWorkstationConfigsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_usable_workstation_configs(self, - request: Optional[Union[workstations.ListUsableWorkstationConfigsRequest, 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.ListUsableWorkstationConfigsAsyncPager: - r"""Returns all workstation configurations in the - specified cluster on which the caller has the - "workstations.workstation.create" permission. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_list_usable_workstation_configs(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListUsableWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstation_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest, dict]]): - The request object. Request message for - ListUsableWorkstationConfigs. - parent (:class:`str`): - Required. Parent resource name. - 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.workstations_v1.services.workstations.pagers.ListUsableWorkstationConfigsAsyncPager: - Response message for - ListUsableWorkstationConfigs. - 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 = workstations.ListUsableWorkstationConfigsRequest(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_usable_workstation_configs, - default_retry=retries.Retry( -initial=1.0,maximum=10.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(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListUsableWorkstationConfigsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_workstation_config(self, - request: Optional[Union[workstations.CreateWorkstationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation_config: Optional[workstations.WorkstationConfig] = None, - workstation_config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_create_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationConfigRequest( - parent="parent_value", - workstation_config_id="workstation_config_id_value", - ) - - # Make the request - operation = client.create_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.CreateWorkstationConfigRequest, dict]]): - The request object. Message for creating a - CreateWorkstationConfig. - parent (:class:`str`): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_config (:class:`google.cloud.workstations_v1.types.WorkstationConfig`): - Required. Config to create. - This corresponds to the ``workstation_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_config_id (:class:`str`): - Required. ID to use for the - workstation configuration. - - This corresponds to the ``workstation_config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.workstations_v1.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. - Workstation configurations are intended to be shared - across multiple workstations. - - """ - # Create or coerce a protobuf request object. - # Quick 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, workstation_config, workstation_config_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = workstations.CreateWorkstationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation_config is not None: - request.workstation_config = workstation_config - if workstation_config_id is not None: - request.workstation_config_id = workstation_config_id - - # 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_workstation_config, - 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(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_workstation_config(self, - request: Optional[Union[workstations.UpdateWorkstationConfigRequest, dict]] = None, - *, - workstation_config: Optional[workstations.WorkstationConfig] = 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 an existing workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_update_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationConfigRequest( - ) - - # Make the request - operation = client.update_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.UpdateWorkstationConfigRequest, dict]]): - The request object. Request message for - UpdateWorkstationConfig. - workstation_config (:class:`google.cloud.workstations_v1.types.WorkstationConfig`): - Required. Config to update. - This corresponds to the ``workstation_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Mask specifying which - fields in the workstation configuration - should 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.workstations_v1.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. - Workstation configurations are intended to be shared - across multiple workstations. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = workstations.UpdateWorkstationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation_config is not None: - request.workstation_config = workstation_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_workstation_config, - 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(( - ("workstation_config.name", request.workstation_config.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, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_workstation_config(self, - request: Optional[Union[workstations.DeleteWorkstationConfigRequest, 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 the specified workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_delete_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.DeleteWorkstationConfigRequest, dict]]): - The request object. Message for deleting a workstation - configuration. - name (:class:`str`): - Required. Name of the workstation - configuration to delete. - - 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.workstations_v1.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. - Workstation configurations are intended to be shared - across multiple workstations. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = workstations.DeleteWorkstationConfigRequest(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_workstation_config, - 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, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_workstation(self, - request: Optional[Union[workstations.GetWorkstationRequest, 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]] = (), - ) -> workstations.Workstation: - r"""Returns the requested workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_get_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.GetWorkstationRequest, dict]]): - The request object. Request message for GetWorkstation. - name (:class:`str`): - Required. Name of the requested - resource. - - 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.workstations_v1.types.Workstation: - A single instance of a developer - workstation with its own persistent - storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = workstations.GetWorkstationRequest(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_workstation, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_workstations(self, - request: Optional[Union[workstations.ListWorkstationsRequest, 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.ListWorkstationsAsyncPager: - r"""Returns all Workstations using the specified - workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_list_workstations(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstations(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.ListWorkstationsRequest, dict]]): - The request object. Request message for ListWorkstations. - parent (:class:`str`): - Required. Parent resource name. - 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.workstations_v1.services.workstations.pagers.ListWorkstationsAsyncPager: - Response message for - ListWorkstations. - 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 = workstations.ListWorkstationsRequest(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_workstations, - default_retry=retries.Retry( -initial=1.0,maximum=10.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(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListWorkstationsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_usable_workstations(self, - request: Optional[Union[workstations.ListUsableWorkstationsRequest, 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.ListUsableWorkstationsAsyncPager: - r"""Returns all workstations using the specified - workstation configuration on which the caller has the - "workstations.workstations.use" permission. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_list_usable_workstations(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListUsableWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstations(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.ListUsableWorkstationsRequest, dict]]): - The request object. Request message for - ListUsableWorkstations. - parent (:class:`str`): - Required. Parent resource name. - 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.workstations_v1.services.workstations.pagers.ListUsableWorkstationsAsyncPager: - Response message for - ListUsableWorkstations. - 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 = workstations.ListUsableWorkstationsRequest(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_usable_workstations, - default_retry=retries.Retry( -initial=1.0,maximum=10.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(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListUsableWorkstationsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_workstation(self, - request: Optional[Union[workstations.CreateWorkstationRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation: Optional[workstations.Workstation] = None, - workstation_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_create_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationRequest( - parent="parent_value", - workstation_id="workstation_id_value", - ) - - # Make the request - operation = client.create_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.CreateWorkstationRequest, dict]]): - The request object. Message for creating a - CreateWorkstation. - parent (:class:`str`): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation (:class:`google.cloud.workstations_v1.types.Workstation`): - Required. Workstation to create. - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_id (:class:`str`): - Required. ID to use for the - workstation. - - This corresponds to the ``workstation_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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, workstation, workstation_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = workstations.CreateWorkstationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation is not None: - request.workstation = workstation - if workstation_id is not None: - request.workstation_id = workstation_id - - # 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_workstation, - 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(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_workstation(self, - request: Optional[Union[workstations.UpdateWorkstationRequest, dict]] = None, - *, - workstation: Optional[workstations.Workstation] = 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 an existing workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_update_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationRequest( - ) - - # Make the request - operation = client.update_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.UpdateWorkstationRequest, dict]]): - The request object. Request message for - UpdateWorkstation. - workstation (:class:`google.cloud.workstations_v1.types.Workstation`): - Required. Workstation to update. - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Mask specifying which - fields in the workstation configuration - should 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.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation, 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 = workstations.UpdateWorkstationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation is not None: - request.workstation = workstation - 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_workstation, - 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(( - ("workstation.name", request.workstation.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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_workstation(self, - request: Optional[Union[workstations.DeleteWorkstationRequest, 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 the specified workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_delete_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.DeleteWorkstationRequest, dict]]): - The request object. Request message for - DeleteWorkstation. - name (:class:`str`): - Required. Name of the workstation to - delete. - - 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.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = workstations.DeleteWorkstationRequest(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_workstation, - 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def start_workstation(self, - request: Optional[Union[workstations.StartWorkstationRequest, 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"""Starts running a workstation so that users can - connect to 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 workstations_v1 - - async def sample_start_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.StartWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.start_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.StartWorkstationRequest, dict]]): - The request object. Request message for StartWorkstation. - name (:class:`str`): - Required. Name of the workstation to - start. - - 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.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = workstations.StartWorkstationRequest(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.start_workstation, - 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def stop_workstation(self, - request: Optional[Union[workstations.StopWorkstationRequest, 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"""Stops running a workstation, reducing costs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_stop_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.StopWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.stop_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.StopWorkstationRequest, dict]]): - The request object. Request message for StopWorkstation. - name (:class:`str`): - Required. Name of the workstation to - stop. - - 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.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = workstations.StopWorkstationRequest(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.stop_workstation, - 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def generate_access_token(self, - request: Optional[Union[workstations.GenerateAccessTokenRequest, dict]] = None, - *, - workstation: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.GenerateAccessTokenResponse: - r"""Returns a short-lived credential that can be used to - send authenticated and authorized traffic to a - workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - async def sample_generate_access_token(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.GenerateAccessTokenRequest( - workstation="workstation_value", - ) - - # Make the request - response = await client.generate_access_token(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1.types.GenerateAccessTokenRequest, dict]]): - The request object. Request message for - GenerateAccessToken. - workstation (:class:`str`): - Required. Name of the workstation for - which the access token should be - generated. - - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1.types.GenerateAccessTokenResponse: - Response message for - GenerateAccessToken. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation]) - if request is 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 = workstations.GenerateAccessTokenRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation is not None: - request.workstation = workstation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.generate_access_token, - default_retry=retries.Retry( -initial=1.0,maximum=10.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(( - ("workstation", request.workstation), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._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) -> "WorkstationsAsyncClient": - 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__ = ( - "WorkstationsAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/client.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/client.py deleted file mode 100644 index 746805281c7b..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/client.py +++ /dev/null @@ -1,3259 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.workstations_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1.services.workstations import pagers -from google.cloud.workstations_v1.types import workstations -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 -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import WorkstationsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import WorkstationsGrpcTransport -from .transports.grpc_asyncio import WorkstationsGrpcAsyncIOTransport -from .transports.rest import WorkstationsRestTransport - - -class WorkstationsClientMeta(type): - """Metaclass for the Workstations 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[WorkstationsTransport]] - _transport_registry["grpc"] = WorkstationsGrpcTransport - _transport_registry["grpc_asyncio"] = WorkstationsGrpcAsyncIOTransport - _transport_registry["rest"] = WorkstationsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[WorkstationsTransport]: - """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 WorkstationsClient(metaclass=WorkstationsClientMeta): - """Service for interacting with Cloud Workstations.""" - - @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 = "workstations.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: - WorkstationsClient: 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: - WorkstationsClient: 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) -> WorkstationsTransport: - """Returns the transport used by the client instance. - - Returns: - WorkstationsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def workstation_path(project: str,location: str,workstation_cluster: str,workstation_config: str,workstation: str,) -> str: - """Returns a fully-qualified workstation string.""" - return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}/workstations/{workstation}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, workstation=workstation, ) - - @staticmethod - def parse_workstation_path(path: str) -> Dict[str,str]: - """Parses a workstation path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)/workstationConfigs/(?P.+?)/workstations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def workstation_cluster_path(project: str,location: str,workstation_cluster: str,) -> str: - """Returns a fully-qualified workstation_cluster string.""" - return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}".format(project=project, location=location, workstation_cluster=workstation_cluster, ) - - @staticmethod - def parse_workstation_cluster_path(path: str) -> Dict[str,str]: - """Parses a workstation_cluster path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def workstation_config_path(project: str,location: str,workstation_cluster: str,workstation_config: str,) -> str: - """Returns a fully-qualified workstation_config string.""" - return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, ) - - @staticmethod - def parse_workstation_config_path(path: str) -> Dict[str,str]: - """Parses a workstation_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)/workstationConfigs/(?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, WorkstationsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the workstations 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, WorkstationsTransport]): 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, WorkstationsTransport): - # transport is a WorkstationsTransport 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_workstation_cluster(self, - request: Optional[Union[workstations.GetWorkstationClusterRequest, 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]] = (), - ) -> workstations.WorkstationCluster: - r"""Returns the requested workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_get_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation_cluster(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.GetWorkstationClusterRequest, dict]): - The request object. Request message for - GetWorkstationCluster. - name (str): - Required. Name of the requested - resource. - - 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.workstations_v1.types.WorkstationCluster: - A grouping of workstation - configurations and the associated - workstations in that region. - - """ - # Create or coerce a protobuf request object. - # Quick 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 workstations.GetWorkstationClusterRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.GetWorkstationClusterRequest): - request = workstations.GetWorkstationClusterRequest(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_workstation_cluster] - - # Certain 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_workstation_clusters(self, - request: Optional[Union[workstations.ListWorkstationClustersRequest, 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.ListWorkstationClustersPager: - r"""Returns all workstation clusters in the specified - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_list_workstation_clusters(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_clusters(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.ListWorkstationClustersRequest, dict]): - The request object. Request message for - ListWorkstationClusters. - parent (str): - Required. Parent resource name. - 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.workstations_v1.services.workstations.pagers.ListWorkstationClustersPager: - Response message for - ListWorkstationClusters. - 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 workstations.ListWorkstationClustersRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.ListWorkstationClustersRequest): - request = workstations.ListWorkstationClustersRequest(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_workstation_clusters] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListWorkstationClustersPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_workstation_cluster(self, - request: Optional[Union[workstations.CreateWorkstationClusterRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation_cluster: Optional[workstations.WorkstationCluster] = None, - workstation_cluster_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_create_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationClusterRequest( - parent="parent_value", - workstation_cluster_id="workstation_cluster_id_value", - ) - - # Make the request - operation = client.create_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.CreateWorkstationClusterRequest, dict]): - The request object. Message for creating a - CreateWorkstationCluster. - parent (str): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_cluster (google.cloud.workstations_v1.types.WorkstationCluster): - Required. Workstation cluster to - create. - - This corresponds to the ``workstation_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_cluster_id (str): - Required. ID to use for the - workstation cluster. - - This corresponds to the ``workstation_cluster_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.workstations_v1.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations - in that region. - - """ - # Create or coerce a protobuf request object. - # Quick 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, workstation_cluster, workstation_cluster_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a workstations.CreateWorkstationClusterRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.CreateWorkstationClusterRequest): - request = workstations.CreateWorkstationClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation_cluster is not None: - request.workstation_cluster = workstation_cluster - if workstation_cluster_id is not None: - request.workstation_cluster_id = workstation_cluster_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_workstation_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_workstation_cluster(self, - request: Optional[Union[workstations.UpdateWorkstationClusterRequest, dict]] = None, - *, - workstation_cluster: Optional[workstations.WorkstationCluster] = 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 an existing workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_update_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationClusterRequest( - ) - - # Make the request - operation = client.update_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.UpdateWorkstationClusterRequest, dict]): - The request object. Request message for - UpdateWorkstationCluster. - workstation_cluster (google.cloud.workstations_v1.types.WorkstationCluster): - Required. Workstation cluster to - update. - - This corresponds to the ``workstation_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask that specifies which - fields in the workstation cluster should - 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.workstations_v1.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations - in that region. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation_cluster, 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 workstations.UpdateWorkstationClusterRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.UpdateWorkstationClusterRequest): - request = workstations.UpdateWorkstationClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation_cluster is not None: - request.workstation_cluster = workstation_cluster - 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_workstation_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation_cluster.name", request.workstation_cluster.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, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_workstation_cluster(self, - request: Optional[Union[workstations.DeleteWorkstationClusterRequest, 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 the specified workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_delete_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.DeleteWorkstationClusterRequest, dict]): - The request object. Message for deleting a workstation - cluster. - name (str): - Required. Name of the workstation - cluster to delete. - - 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.workstations_v1.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations - in that region. - - """ - # Create or coerce a protobuf request object. - # Quick 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 workstations.DeleteWorkstationClusterRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.DeleteWorkstationClusterRequest): - request = workstations.DeleteWorkstationClusterRequest(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_workstation_cluster] - - # Certain 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, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_workstation_config(self, - request: Optional[Union[workstations.GetWorkstationConfigRequest, 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]] = (), - ) -> workstations.WorkstationConfig: - r"""Returns the requested workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_get_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.GetWorkstationConfigRequest, dict]): - The request object. Request message for - GetWorkstationConfig. - name (str): - Required. Name of the requested - resource. - - 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.workstations_v1.types.WorkstationConfig: - A set of configuration options - describing how a workstation will be - run. Workstation configurations are - intended to be shared across multiple - workstations. - - """ - # Create or coerce a protobuf request object. - # Quick 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 workstations.GetWorkstationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.GetWorkstationConfigRequest): - request = workstations.GetWorkstationConfigRequest(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_workstation_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_workstation_configs(self, - request: Optional[Union[workstations.ListWorkstationConfigsRequest, 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.ListWorkstationConfigsPager: - r"""Returns all workstation configurations in the - specified cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_list_workstation_configs(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.ListWorkstationConfigsRequest, dict]): - The request object. Request message for - ListWorkstationConfigs. - parent (str): - Required. Parent resource name. - 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.workstations_v1.services.workstations.pagers.ListWorkstationConfigsPager: - Response message for - ListWorkstationConfigs. - 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 workstations.ListWorkstationConfigsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.ListWorkstationConfigsRequest): - request = workstations.ListWorkstationConfigsRequest(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_workstation_configs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListWorkstationConfigsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_usable_workstation_configs(self, - request: Optional[Union[workstations.ListUsableWorkstationConfigsRequest, 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.ListUsableWorkstationConfigsPager: - r"""Returns all workstation configurations in the - specified cluster on which the caller has the - "workstations.workstation.create" permission. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_list_usable_workstation_configs(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListUsableWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstation_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest, dict]): - The request object. Request message for - ListUsableWorkstationConfigs. - parent (str): - Required. Parent resource name. - 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.workstations_v1.services.workstations.pagers.ListUsableWorkstationConfigsPager: - Response message for - ListUsableWorkstationConfigs. - 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 workstations.ListUsableWorkstationConfigsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.ListUsableWorkstationConfigsRequest): - request = workstations.ListUsableWorkstationConfigsRequest(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_usable_workstation_configs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListUsableWorkstationConfigsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_workstation_config(self, - request: Optional[Union[workstations.CreateWorkstationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation_config: Optional[workstations.WorkstationConfig] = None, - workstation_config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_create_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationConfigRequest( - parent="parent_value", - workstation_config_id="workstation_config_id_value", - ) - - # Make the request - operation = client.create_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.CreateWorkstationConfigRequest, dict]): - The request object. Message for creating a - CreateWorkstationConfig. - parent (str): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_config (google.cloud.workstations_v1.types.WorkstationConfig): - Required. Config to create. - This corresponds to the ``workstation_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_config_id (str): - Required. ID to use for the - workstation configuration. - - This corresponds to the ``workstation_config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.workstations_v1.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. - Workstation configurations are intended to be shared - across multiple workstations. - - """ - # Create or coerce a protobuf request object. - # Quick 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, workstation_config, workstation_config_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a workstations.CreateWorkstationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.CreateWorkstationConfigRequest): - request = workstations.CreateWorkstationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation_config is not None: - request.workstation_config = workstation_config - if workstation_config_id is not None: - request.workstation_config_id = workstation_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_workstation_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # 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, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_workstation_config(self, - request: Optional[Union[workstations.UpdateWorkstationConfigRequest, dict]] = None, - *, - workstation_config: Optional[workstations.WorkstationConfig] = 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 an existing workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_update_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationConfigRequest( - ) - - # Make the request - operation = client.update_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.UpdateWorkstationConfigRequest, dict]): - The request object. Request message for - UpdateWorkstationConfig. - workstation_config (google.cloud.workstations_v1.types.WorkstationConfig): - Required. Config to update. - This corresponds to the ``workstation_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask specifying which - fields in the workstation configuration - should 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.workstations_v1.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. - Workstation configurations are intended to be shared - across multiple workstations. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a workstations.UpdateWorkstationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.UpdateWorkstationConfigRequest): - request = workstations.UpdateWorkstationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation_config is not None: - request.workstation_config = workstation_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_workstation_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation_config.name", request.workstation_config.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, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_workstation_config(self, - request: Optional[Union[workstations.DeleteWorkstationConfigRequest, 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 the specified workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_delete_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.DeleteWorkstationConfigRequest, dict]): - The request object. Message for deleting a workstation - configuration. - name (str): - Required. Name of the workstation - configuration to delete. - - 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.workstations_v1.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. - Workstation configurations are intended to be shared - across multiple workstations. - - """ - # Create or coerce a protobuf request object. - # Quick 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 workstations.DeleteWorkstationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.DeleteWorkstationConfigRequest): - request = workstations.DeleteWorkstationConfigRequest(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_workstation_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # 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, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_workstation(self, - request: Optional[Union[workstations.GetWorkstationRequest, 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]] = (), - ) -> workstations.Workstation: - r"""Returns the requested workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_get_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.GetWorkstationRequest, dict]): - The request object. Request message for GetWorkstation. - name (str): - Required. Name of the requested - resource. - - 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.workstations_v1.types.Workstation: - A single instance of a developer - workstation with its own persistent - storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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 workstations.GetWorkstationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.GetWorkstationRequest): - request = workstations.GetWorkstationRequest(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_workstation] - - # Certain 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_workstations(self, - request: Optional[Union[workstations.ListWorkstationsRequest, 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.ListWorkstationsPager: - r"""Returns all Workstations using the specified - workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_list_workstations(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstations(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.ListWorkstationsRequest, dict]): - The request object. Request message for ListWorkstations. - parent (str): - Required. Parent resource name. - 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.workstations_v1.services.workstations.pagers.ListWorkstationsPager: - Response message for - ListWorkstations. - 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 workstations.ListWorkstationsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.ListWorkstationsRequest): - request = workstations.ListWorkstationsRequest(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_workstations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListWorkstationsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_usable_workstations(self, - request: Optional[Union[workstations.ListUsableWorkstationsRequest, 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.ListUsableWorkstationsPager: - r"""Returns all workstations using the specified - workstation configuration on which the caller has the - "workstations.workstations.use" permission. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_list_usable_workstations(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListUsableWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstations(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.ListUsableWorkstationsRequest, dict]): - The request object. Request message for - ListUsableWorkstations. - parent (str): - Required. Parent resource name. - 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.workstations_v1.services.workstations.pagers.ListUsableWorkstationsPager: - Response message for - ListUsableWorkstations. - 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 workstations.ListUsableWorkstationsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.ListUsableWorkstationsRequest): - request = workstations.ListUsableWorkstationsRequest(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_usable_workstations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListUsableWorkstationsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_workstation(self, - request: Optional[Union[workstations.CreateWorkstationRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation: Optional[workstations.Workstation] = None, - workstation_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_create_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationRequest( - parent="parent_value", - workstation_id="workstation_id_value", - ) - - # Make the request - operation = client.create_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.CreateWorkstationRequest, dict]): - The request object. Message for creating a - CreateWorkstation. - parent (str): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation (google.cloud.workstations_v1.types.Workstation): - Required. Workstation to create. - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_id (str): - Required. ID to use for the - workstation. - - This corresponds to the ``workstation_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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, workstation, workstation_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a workstations.CreateWorkstationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.CreateWorkstationRequest): - request = workstations.CreateWorkstationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation is not None: - request.workstation = workstation - if workstation_id is not None: - request.workstation_id = workstation_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_workstation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_workstation(self, - request: Optional[Union[workstations.UpdateWorkstationRequest, dict]] = None, - *, - workstation: Optional[workstations.Workstation] = 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 an existing workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_update_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationRequest( - ) - - # Make the request - operation = client.update_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.UpdateWorkstationRequest, dict]): - The request object. Request message for - UpdateWorkstation. - workstation (google.cloud.workstations_v1.types.Workstation): - Required. Workstation to update. - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask specifying which - fields in the workstation configuration - should 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.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation, 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 workstations.UpdateWorkstationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.UpdateWorkstationRequest): - request = workstations.UpdateWorkstationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation is not None: - request.workstation = workstation - 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_workstation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation.name", request.workstation.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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_workstation(self, - request: Optional[Union[workstations.DeleteWorkstationRequest, 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 the specified workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_delete_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.DeleteWorkstationRequest, dict]): - The request object. Request message for - DeleteWorkstation. - name (str): - Required. Name of the workstation to - delete. - - 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.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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 workstations.DeleteWorkstationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.DeleteWorkstationRequest): - request = workstations.DeleteWorkstationRequest(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_workstation] - - # Certain 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def start_workstation(self, - request: Optional[Union[workstations.StartWorkstationRequest, 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"""Starts running a workstation so that users can - connect to 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 workstations_v1 - - def sample_start_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.StartWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.start_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.StartWorkstationRequest, dict]): - The request object. Request message for StartWorkstation. - name (str): - Required. Name of the workstation to - start. - - 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.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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 workstations.StartWorkstationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.StartWorkstationRequest): - request = workstations.StartWorkstationRequest(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.start_workstation] - - # Certain 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def stop_workstation(self, - request: Optional[Union[workstations.StopWorkstationRequest, 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"""Stops running a workstation, reducing costs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_stop_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.StopWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.stop_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.StopWorkstationRequest, dict]): - The request object. Request message for StopWorkstation. - name (str): - Required. Name of the workstation to - stop. - - 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.workstations_v1.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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 workstations.StopWorkstationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.StopWorkstationRequest): - request = workstations.StopWorkstationRequest(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.stop_workstation] - - # Certain 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def generate_access_token(self, - request: Optional[Union[workstations.GenerateAccessTokenRequest, dict]] = None, - *, - workstation: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.GenerateAccessTokenResponse: - r"""Returns a short-lived credential that can be used to - send authenticated and authorized traffic to a - workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1 - - def sample_generate_access_token(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.GenerateAccessTokenRequest( - workstation="workstation_value", - ) - - # Make the request - response = client.generate_access_token(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1.types.GenerateAccessTokenRequest, dict]): - The request object. Request message for - GenerateAccessToken. - workstation (str): - Required. Name of the workstation for - which the access token should be - generated. - - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1.types.GenerateAccessTokenResponse: - Response message for - GenerateAccessToken. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation]) - if request is 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 workstations.GenerateAccessTokenRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.GenerateAccessTokenRequest): - request = workstations.GenerateAccessTokenRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation is not None: - request.workstation = workstation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_access_token] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation", request.workstation), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "WorkstationsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "WorkstationsClient", -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/pagers.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/pagers.py deleted file mode 100644 index 1d2bafb58129..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/pagers.py +++ /dev/null @@ -1,623 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.workstations_v1.types import workstations - - -class ListWorkstationClustersPager: - """A pager for iterating through ``list_workstation_clusters`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListWorkstationClustersResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstation_clusters`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListWorkstationClusters`` requests and continue to iterate - through the ``workstation_clusters`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationClustersResponse` - 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[..., workstations.ListWorkstationClustersResponse], - request: workstations.ListWorkstationClustersRequest, - response: workstations.ListWorkstationClustersResponse, - *, - 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.workstations_v1.types.ListWorkstationClustersRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListWorkstationClustersResponse): - 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 = workstations.ListWorkstationClustersRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[workstations.ListWorkstationClustersResponse]: - 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[workstations.WorkstationCluster]: - for page in self.pages: - yield from page.workstation_clusters - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationClustersAsyncPager: - """A pager for iterating through ``list_workstation_clusters`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListWorkstationClustersResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstation_clusters`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListWorkstationClusters`` requests and continue to iterate - through the ``workstation_clusters`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationClustersResponse` - 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[workstations.ListWorkstationClustersResponse]], - request: workstations.ListWorkstationClustersRequest, - response: workstations.ListWorkstationClustersResponse, - *, - 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.workstations_v1.types.ListWorkstationClustersRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListWorkstationClustersResponse): - 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 = workstations.ListWorkstationClustersRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[workstations.ListWorkstationClustersResponse]: - 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[workstations.WorkstationCluster]: - async def async_generator(): - async for page in self.pages: - for response in page.workstation_clusters: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationConfigsPager: - """A pager for iterating through ``list_workstation_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListWorkstationConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstation_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListWorkstationConfigs`` requests and continue to iterate - through the ``workstation_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationConfigsResponse` - 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[..., workstations.ListWorkstationConfigsResponse], - request: workstations.ListWorkstationConfigsRequest, - response: workstations.ListWorkstationConfigsResponse, - *, - 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.workstations_v1.types.ListWorkstationConfigsRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListWorkstationConfigsResponse): - 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 = workstations.ListWorkstationConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[workstations.ListWorkstationConfigsResponse]: - 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[workstations.WorkstationConfig]: - for page in self.pages: - yield from page.workstation_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationConfigsAsyncPager: - """A pager for iterating through ``list_workstation_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListWorkstationConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstation_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListWorkstationConfigs`` requests and continue to iterate - through the ``workstation_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationConfigsResponse` - 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[workstations.ListWorkstationConfigsResponse]], - request: workstations.ListWorkstationConfigsRequest, - response: workstations.ListWorkstationConfigsResponse, - *, - 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.workstations_v1.types.ListWorkstationConfigsRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListWorkstationConfigsResponse): - 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 = workstations.ListWorkstationConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[workstations.ListWorkstationConfigsResponse]: - 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[workstations.WorkstationConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.workstation_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUsableWorkstationConfigsPager: - """A pager for iterating through ``list_usable_workstation_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstation_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListUsableWorkstationConfigs`` requests and continue to iterate - through the ``workstation_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse` - 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[..., workstations.ListUsableWorkstationConfigsResponse], - request: workstations.ListUsableWorkstationConfigsRequest, - response: workstations.ListUsableWorkstationConfigsResponse, - *, - 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.workstations_v1.types.ListUsableWorkstationConfigsRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse): - 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 = workstations.ListUsableWorkstationConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[workstations.ListUsableWorkstationConfigsResponse]: - 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[workstations.WorkstationConfig]: - for page in self.pages: - yield from page.workstation_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUsableWorkstationConfigsAsyncPager: - """A pager for iterating through ``list_usable_workstation_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstation_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListUsableWorkstationConfigs`` requests and continue to iterate - through the ``workstation_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse` - 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[workstations.ListUsableWorkstationConfigsResponse]], - request: workstations.ListUsableWorkstationConfigsRequest, - response: workstations.ListUsableWorkstationConfigsResponse, - *, - 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.workstations_v1.types.ListUsableWorkstationConfigsRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListUsableWorkstationConfigsResponse): - 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 = workstations.ListUsableWorkstationConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[workstations.ListUsableWorkstationConfigsResponse]: - 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[workstations.WorkstationConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.workstation_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationsPager: - """A pager for iterating through ``list_workstations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListWorkstationsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstations`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListWorkstations`` requests and continue to iterate - through the ``workstations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationsResponse` - 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[..., workstations.ListWorkstationsResponse], - request: workstations.ListWorkstationsRequest, - response: workstations.ListWorkstationsResponse, - *, - 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.workstations_v1.types.ListWorkstationsRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListWorkstationsResponse): - 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 = workstations.ListWorkstationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[workstations.ListWorkstationsResponse]: - 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[workstations.Workstation]: - for page in self.pages: - yield from page.workstations - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationsAsyncPager: - """A pager for iterating through ``list_workstations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListWorkstationsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstations`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListWorkstations`` requests and continue to iterate - through the ``workstations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListWorkstationsResponse` - 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[workstations.ListWorkstationsResponse]], - request: workstations.ListWorkstationsRequest, - response: workstations.ListWorkstationsResponse, - *, - 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.workstations_v1.types.ListWorkstationsRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListWorkstationsResponse): - 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 = workstations.ListWorkstationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[workstations.ListWorkstationsResponse]: - 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[workstations.Workstation]: - async def async_generator(): - async for page in self.pages: - for response in page.workstations: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUsableWorkstationsPager: - """A pager for iterating through ``list_usable_workstations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListUsableWorkstationsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstations`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListUsableWorkstations`` requests and continue to iterate - through the ``workstations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListUsableWorkstationsResponse` - 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[..., workstations.ListUsableWorkstationsResponse], - request: workstations.ListUsableWorkstationsRequest, - response: workstations.ListUsableWorkstationsResponse, - *, - 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.workstations_v1.types.ListUsableWorkstationsRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListUsableWorkstationsResponse): - 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 = workstations.ListUsableWorkstationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[workstations.ListUsableWorkstationsResponse]: - 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[workstations.Workstation]: - for page in self.pages: - yield from page.workstations - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUsableWorkstationsAsyncPager: - """A pager for iterating through ``list_usable_workstations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1.types.ListUsableWorkstationsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstations`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListUsableWorkstations`` requests and continue to iterate - through the ``workstations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1.types.ListUsableWorkstationsResponse` - 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[workstations.ListUsableWorkstationsResponse]], - request: workstations.ListUsableWorkstationsRequest, - response: workstations.ListUsableWorkstationsResponse, - *, - 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.workstations_v1.types.ListUsableWorkstationsRequest): - The initial request object. - response (google.cloud.workstations_v1.types.ListUsableWorkstationsResponse): - 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 = workstations.ListUsableWorkstationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[workstations.ListUsableWorkstationsResponse]: - 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[workstations.Workstation]: - async def async_generator(): - async for page in self.pages: - for response in page.workstations: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/__init__.py deleted file mode 100644 index fc931d51cd5e..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 WorkstationsTransport -from .grpc import WorkstationsGrpcTransport -from .grpc_asyncio import WorkstationsGrpcAsyncIOTransport -from .rest import WorkstationsRestTransport -from .rest import WorkstationsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[WorkstationsTransport]] -_transport_registry['grpc'] = WorkstationsGrpcTransport -_transport_registry['grpc_asyncio'] = WorkstationsGrpcAsyncIOTransport -_transport_registry['rest'] = WorkstationsRestTransport - -__all__ = ( - 'WorkstationsTransport', - 'WorkstationsGrpcTransport', - 'WorkstationsGrpcAsyncIOTransport', - 'WorkstationsRestTransport', - 'WorkstationsRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/base.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/base.py deleted file mode 100644 index 0a8e7d09a29d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/base.py +++ /dev/null @@ -1,545 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.workstations_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1.types import workstations -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 -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class WorkstationsTransport(abc.ABC): - """Abstract transport class for Workstations.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'workstations.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_workstation_cluster: gapic_v1.method.wrap_method( - self.get_workstation_cluster, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_workstation_clusters: gapic_v1.method.wrap_method( - self.list_workstation_clusters, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_workstation_cluster: gapic_v1.method.wrap_method( - self.create_workstation_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.update_workstation_cluster: gapic_v1.method.wrap_method( - self.update_workstation_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_workstation_cluster: gapic_v1.method.wrap_method( - self.delete_workstation_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.get_workstation_config: gapic_v1.method.wrap_method( - self.get_workstation_config, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_workstation_configs: gapic_v1.method.wrap_method( - self.list_workstation_configs, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_usable_workstation_configs: gapic_v1.method.wrap_method( - self.list_usable_workstation_configs, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_workstation_config: gapic_v1.method.wrap_method( - self.create_workstation_config, - default_timeout=60.0, - client_info=client_info, - ), - self.update_workstation_config: gapic_v1.method.wrap_method( - self.update_workstation_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_workstation_config: gapic_v1.method.wrap_method( - self.delete_workstation_config, - default_timeout=60.0, - client_info=client_info, - ), - self.get_workstation: gapic_v1.method.wrap_method( - self.get_workstation, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_workstations: gapic_v1.method.wrap_method( - self.list_workstations, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_usable_workstations: gapic_v1.method.wrap_method( - self.list_usable_workstations, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_workstation: gapic_v1.method.wrap_method( - self.create_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.update_workstation: gapic_v1.method.wrap_method( - self.update_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_workstation: gapic_v1.method.wrap_method( - self.delete_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.start_workstation: gapic_v1.method.wrap_method( - self.start_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.stop_workstation: gapic_v1.method.wrap_method( - self.stop_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.generate_access_token: gapic_v1.method.wrap_method( - self.generate_access_token, - default_retry=retries.Retry( -initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - 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 get_workstation_cluster(self) -> Callable[ - [workstations.GetWorkstationClusterRequest], - Union[ - workstations.WorkstationCluster, - Awaitable[workstations.WorkstationCluster] - ]]: - raise NotImplementedError() - - @property - def list_workstation_clusters(self) -> Callable[ - [workstations.ListWorkstationClustersRequest], - Union[ - workstations.ListWorkstationClustersResponse, - Awaitable[workstations.ListWorkstationClustersResponse] - ]]: - raise NotImplementedError() - - @property - def create_workstation_cluster(self) -> Callable[ - [workstations.CreateWorkstationClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_workstation_cluster(self) -> Callable[ - [workstations.UpdateWorkstationClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_workstation_cluster(self) -> Callable[ - [workstations.DeleteWorkstationClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_workstation_config(self) -> Callable[ - [workstations.GetWorkstationConfigRequest], - Union[ - workstations.WorkstationConfig, - Awaitable[workstations.WorkstationConfig] - ]]: - raise NotImplementedError() - - @property - def list_workstation_configs(self) -> Callable[ - [workstations.ListWorkstationConfigsRequest], - Union[ - workstations.ListWorkstationConfigsResponse, - Awaitable[workstations.ListWorkstationConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def list_usable_workstation_configs(self) -> Callable[ - [workstations.ListUsableWorkstationConfigsRequest], - Union[ - workstations.ListUsableWorkstationConfigsResponse, - Awaitable[workstations.ListUsableWorkstationConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def create_workstation_config(self) -> Callable[ - [workstations.CreateWorkstationConfigRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_workstation_config(self) -> Callable[ - [workstations.UpdateWorkstationConfigRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_workstation_config(self) -> Callable[ - [workstations.DeleteWorkstationConfigRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_workstation(self) -> Callable[ - [workstations.GetWorkstationRequest], - Union[ - workstations.Workstation, - Awaitable[workstations.Workstation] - ]]: - raise NotImplementedError() - - @property - def list_workstations(self) -> Callable[ - [workstations.ListWorkstationsRequest], - Union[ - workstations.ListWorkstationsResponse, - Awaitable[workstations.ListWorkstationsResponse] - ]]: - raise NotImplementedError() - - @property - def list_usable_workstations(self) -> Callable[ - [workstations.ListUsableWorkstationsRequest], - Union[ - workstations.ListUsableWorkstationsResponse, - Awaitable[workstations.ListUsableWorkstationsResponse] - ]]: - raise NotImplementedError() - - @property - def create_workstation(self) -> Callable[ - [workstations.CreateWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_workstation(self) -> Callable[ - [workstations.UpdateWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_workstation(self) -> Callable[ - [workstations.DeleteWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def start_workstation(self) -> Callable[ - [workstations.StartWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def stop_workstation(self) -> Callable[ - [workstations.StopWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def generate_access_token(self) -> Callable[ - [workstations.GenerateAccessTokenRequest], - Union[ - workstations.GenerateAccessTokenResponse, - Awaitable[workstations.GenerateAccessTokenResponse] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def delete_operation( - self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def set_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse], - ], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'WorkstationsTransport', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc.py deleted file mode 100644 index c35226b36b23..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc.py +++ /dev/null @@ -1,943 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1.types import workstations -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 -from google.longrunning import operations_pb2 # type: ignore -from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO - - -class WorkstationsGrpcTransport(WorkstationsTransport): - """gRPC backend transport for Workstations. - - Service for interacting with Cloud Workstations. - - 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 = 'workstations.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 = 'workstations.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_workstation_cluster(self) -> Callable[ - [workstations.GetWorkstationClusterRequest], - workstations.WorkstationCluster]: - r"""Return a callable for the get workstation cluster method over gRPC. - - Returns the requested workstation cluster. - - Returns: - Callable[[~.GetWorkstationClusterRequest], - ~.WorkstationCluster]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: - self._stubs['get_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/GetWorkstationCluster', - request_serializer=workstations.GetWorkstationClusterRequest.serialize, - response_deserializer=workstations.WorkstationCluster.deserialize, - ) - return self._stubs['get_workstation_cluster'] - - @property - def list_workstation_clusters(self) -> Callable[ - [workstations.ListWorkstationClustersRequest], - workstations.ListWorkstationClustersResponse]: - r"""Return a callable for the list workstation clusters method over gRPC. - - Returns all workstation clusters in the specified - location. - - Returns: - Callable[[~.ListWorkstationClustersRequest], - ~.ListWorkstationClustersResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_clusters' not in self._stubs: - self._stubs['list_workstation_clusters'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListWorkstationClusters', - request_serializer=workstations.ListWorkstationClustersRequest.serialize, - response_deserializer=workstations.ListWorkstationClustersResponse.deserialize, - ) - return self._stubs['list_workstation_clusters'] - - @property - def create_workstation_cluster(self) -> Callable[ - [workstations.CreateWorkstationClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the create workstation cluster method over gRPC. - - Creates a new workstation cluster. - - Returns: - Callable[[~.CreateWorkstationClusterRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: - self._stubs['create_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/CreateWorkstationCluster', - request_serializer=workstations.CreateWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation_cluster'] - - @property - def update_workstation_cluster(self) -> Callable[ - [workstations.UpdateWorkstationClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the update workstation cluster method over gRPC. - - Updates an existing workstation cluster. - - Returns: - Callable[[~.UpdateWorkstationClusterRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: - self._stubs['update_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/UpdateWorkstationCluster', - request_serializer=workstations.UpdateWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation_cluster'] - - @property - def delete_workstation_cluster(self) -> Callable[ - [workstations.DeleteWorkstationClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete workstation cluster method over gRPC. - - Deletes the specified workstation cluster. - - Returns: - Callable[[~.DeleteWorkstationClusterRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: - self._stubs['delete_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/DeleteWorkstationCluster', - request_serializer=workstations.DeleteWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation_cluster'] - - @property - def get_workstation_config(self) -> Callable[ - [workstations.GetWorkstationConfigRequest], - workstations.WorkstationConfig]: - r"""Return a callable for the get workstation config method over gRPC. - - Returns the requested workstation configuration. - - Returns: - Callable[[~.GetWorkstationConfigRequest], - ~.WorkstationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: - self._stubs['get_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/GetWorkstationConfig', - request_serializer=workstations.GetWorkstationConfigRequest.serialize, - response_deserializer=workstations.WorkstationConfig.deserialize, - ) - return self._stubs['get_workstation_config'] - - @property - def list_workstation_configs(self) -> Callable[ - [workstations.ListWorkstationConfigsRequest], - workstations.ListWorkstationConfigsResponse]: - r"""Return a callable for the list workstation configs method over gRPC. - - Returns all workstation configurations in the - specified cluster. - - Returns: - Callable[[~.ListWorkstationConfigsRequest], - ~.ListWorkstationConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_configs' not in self._stubs: - self._stubs['list_workstation_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListWorkstationConfigs', - request_serializer=workstations.ListWorkstationConfigsRequest.serialize, - response_deserializer=workstations.ListWorkstationConfigsResponse.deserialize, - ) - return self._stubs['list_workstation_configs'] - - @property - def list_usable_workstation_configs(self) -> Callable[ - [workstations.ListUsableWorkstationConfigsRequest], - workstations.ListUsableWorkstationConfigsResponse]: - r"""Return a callable for the list usable workstation - configs method over gRPC. - - Returns all workstation configurations in the - specified cluster on which the caller has the - "workstations.workstation.create" permission. - - Returns: - Callable[[~.ListUsableWorkstationConfigsRequest], - ~.ListUsableWorkstationConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_usable_workstation_configs' not in self._stubs: - self._stubs['list_usable_workstation_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListUsableWorkstationConfigs', - request_serializer=workstations.ListUsableWorkstationConfigsRequest.serialize, - response_deserializer=workstations.ListUsableWorkstationConfigsResponse.deserialize, - ) - return self._stubs['list_usable_workstation_configs'] - - @property - def create_workstation_config(self) -> Callable[ - [workstations.CreateWorkstationConfigRequest], - operations_pb2.Operation]: - r"""Return a callable for the create workstation config method over gRPC. - - Creates a new workstation configuration. - - Returns: - Callable[[~.CreateWorkstationConfigRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: - self._stubs['create_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/CreateWorkstationConfig', - request_serializer=workstations.CreateWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation_config'] - - @property - def update_workstation_config(self) -> Callable[ - [workstations.UpdateWorkstationConfigRequest], - operations_pb2.Operation]: - r"""Return a callable for the update workstation config method over gRPC. - - Updates an existing workstation configuration. - - Returns: - Callable[[~.UpdateWorkstationConfigRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: - self._stubs['update_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/UpdateWorkstationConfig', - request_serializer=workstations.UpdateWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation_config'] - - @property - def delete_workstation_config(self) -> Callable[ - [workstations.DeleteWorkstationConfigRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete workstation config method over gRPC. - - Deletes the specified workstation configuration. - - Returns: - Callable[[~.DeleteWorkstationConfigRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: - self._stubs['delete_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/DeleteWorkstationConfig', - request_serializer=workstations.DeleteWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation_config'] - - @property - def get_workstation(self) -> Callable[ - [workstations.GetWorkstationRequest], - workstations.Workstation]: - r"""Return a callable for the get workstation method over gRPC. - - Returns the requested workstation. - - Returns: - Callable[[~.GetWorkstationRequest], - ~.Workstation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation' not in self._stubs: - self._stubs['get_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/GetWorkstation', - request_serializer=workstations.GetWorkstationRequest.serialize, - response_deserializer=workstations.Workstation.deserialize, - ) - return self._stubs['get_workstation'] - - @property - def list_workstations(self) -> Callable[ - [workstations.ListWorkstationsRequest], - workstations.ListWorkstationsResponse]: - r"""Return a callable for the list workstations method over gRPC. - - Returns all Workstations using the specified - workstation configuration. - - Returns: - Callable[[~.ListWorkstationsRequest], - ~.ListWorkstationsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstations' not in self._stubs: - self._stubs['list_workstations'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListWorkstations', - request_serializer=workstations.ListWorkstationsRequest.serialize, - response_deserializer=workstations.ListWorkstationsResponse.deserialize, - ) - return self._stubs['list_workstations'] - - @property - def list_usable_workstations(self) -> Callable[ - [workstations.ListUsableWorkstationsRequest], - workstations.ListUsableWorkstationsResponse]: - r"""Return a callable for the list usable workstations method over gRPC. - - Returns all workstations using the specified - workstation configuration on which the caller has the - "workstations.workstations.use" permission. - - Returns: - Callable[[~.ListUsableWorkstationsRequest], - ~.ListUsableWorkstationsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_usable_workstations' not in self._stubs: - self._stubs['list_usable_workstations'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListUsableWorkstations', - request_serializer=workstations.ListUsableWorkstationsRequest.serialize, - response_deserializer=workstations.ListUsableWorkstationsResponse.deserialize, - ) - return self._stubs['list_usable_workstations'] - - @property - def create_workstation(self) -> Callable[ - [workstations.CreateWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the create workstation method over gRPC. - - Creates a new workstation. - - Returns: - Callable[[~.CreateWorkstationRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation' not in self._stubs: - self._stubs['create_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/CreateWorkstation', - request_serializer=workstations.CreateWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation'] - - @property - def update_workstation(self) -> Callable[ - [workstations.UpdateWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the update workstation method over gRPC. - - Updates an existing workstation. - - Returns: - Callable[[~.UpdateWorkstationRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation' not in self._stubs: - self._stubs['update_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/UpdateWorkstation', - request_serializer=workstations.UpdateWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation'] - - @property - def delete_workstation(self) -> Callable[ - [workstations.DeleteWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete workstation method over gRPC. - - Deletes the specified workstation. - - Returns: - Callable[[~.DeleteWorkstationRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation' not in self._stubs: - self._stubs['delete_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/DeleteWorkstation', - request_serializer=workstations.DeleteWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation'] - - @property - def start_workstation(self) -> Callable[ - [workstations.StartWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the start workstation method over gRPC. - - Starts running a workstation so that users can - connect to it. - - Returns: - Callable[[~.StartWorkstationRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_workstation' not in self._stubs: - self._stubs['start_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/StartWorkstation', - request_serializer=workstations.StartWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['start_workstation'] - - @property - def stop_workstation(self) -> Callable[ - [workstations.StopWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the stop workstation method over gRPC. - - Stops running a workstation, reducing costs. - - Returns: - Callable[[~.StopWorkstationRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_workstation' not in self._stubs: - self._stubs['stop_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/StopWorkstation', - request_serializer=workstations.StopWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['stop_workstation'] - - @property - def generate_access_token(self) -> Callable[ - [workstations.GenerateAccessTokenRequest], - workstations.GenerateAccessTokenResponse]: - r"""Return a callable for the generate access token method over gRPC. - - Returns a short-lived credential that can be used to - send authenticated and authorized traffic to a - workstation. - - Returns: - Callable[[~.GenerateAccessTokenRequest], - ~.GenerateAccessTokenResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_access_token' not in self._stubs: - self._stubs['generate_access_token'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/GenerateAccessToken', - request_serializer=workstations.GenerateAccessTokenRequest.serialize, - response_deserializer=workstations.GenerateAccessTokenResponse.deserialize, - ) - return self._stubs['generate_access_token'] - - def close(self): - self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'WorkstationsGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc_asyncio.py deleted file mode 100644 index ee4f5cfb2018..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/grpc_asyncio.py +++ /dev/null @@ -1,942 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1.types import workstations -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 -from google.longrunning import operations_pb2 # type: ignore -from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO -from .grpc import WorkstationsGrpcTransport - - -class WorkstationsGrpcAsyncIOTransport(WorkstationsTransport): - """gRPC AsyncIO backend transport for Workstations. - - Service for interacting with Cloud Workstations. - - 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 = 'workstations.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 = 'workstations.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_workstation_cluster(self) -> Callable[ - [workstations.GetWorkstationClusterRequest], - Awaitable[workstations.WorkstationCluster]]: - r"""Return a callable for the get workstation cluster method over gRPC. - - Returns the requested workstation cluster. - - Returns: - Callable[[~.GetWorkstationClusterRequest], - Awaitable[~.WorkstationCluster]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: - self._stubs['get_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/GetWorkstationCluster', - request_serializer=workstations.GetWorkstationClusterRequest.serialize, - response_deserializer=workstations.WorkstationCluster.deserialize, - ) - return self._stubs['get_workstation_cluster'] - - @property - def list_workstation_clusters(self) -> Callable[ - [workstations.ListWorkstationClustersRequest], - Awaitable[workstations.ListWorkstationClustersResponse]]: - r"""Return a callable for the list workstation clusters method over gRPC. - - Returns all workstation clusters in the specified - location. - - Returns: - Callable[[~.ListWorkstationClustersRequest], - Awaitable[~.ListWorkstationClustersResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_clusters' not in self._stubs: - self._stubs['list_workstation_clusters'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListWorkstationClusters', - request_serializer=workstations.ListWorkstationClustersRequest.serialize, - response_deserializer=workstations.ListWorkstationClustersResponse.deserialize, - ) - return self._stubs['list_workstation_clusters'] - - @property - def create_workstation_cluster(self) -> Callable[ - [workstations.CreateWorkstationClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create workstation cluster method over gRPC. - - Creates a new workstation cluster. - - Returns: - Callable[[~.CreateWorkstationClusterRequest], - 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_workstation_cluster' not in self._stubs: - self._stubs['create_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/CreateWorkstationCluster', - request_serializer=workstations.CreateWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation_cluster'] - - @property - def update_workstation_cluster(self) -> Callable[ - [workstations.UpdateWorkstationClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update workstation cluster method over gRPC. - - Updates an existing workstation cluster. - - Returns: - Callable[[~.UpdateWorkstationClusterRequest], - 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_workstation_cluster' not in self._stubs: - self._stubs['update_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/UpdateWorkstationCluster', - request_serializer=workstations.UpdateWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation_cluster'] - - @property - def delete_workstation_cluster(self) -> Callable[ - [workstations.DeleteWorkstationClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete workstation cluster method over gRPC. - - Deletes the specified workstation cluster. - - Returns: - Callable[[~.DeleteWorkstationClusterRequest], - 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_workstation_cluster' not in self._stubs: - self._stubs['delete_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/DeleteWorkstationCluster', - request_serializer=workstations.DeleteWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation_cluster'] - - @property - def get_workstation_config(self) -> Callable[ - [workstations.GetWorkstationConfigRequest], - Awaitable[workstations.WorkstationConfig]]: - r"""Return a callable for the get workstation config method over gRPC. - - Returns the requested workstation configuration. - - Returns: - Callable[[~.GetWorkstationConfigRequest], - Awaitable[~.WorkstationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: - self._stubs['get_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/GetWorkstationConfig', - request_serializer=workstations.GetWorkstationConfigRequest.serialize, - response_deserializer=workstations.WorkstationConfig.deserialize, - ) - return self._stubs['get_workstation_config'] - - @property - def list_workstation_configs(self) -> Callable[ - [workstations.ListWorkstationConfigsRequest], - Awaitable[workstations.ListWorkstationConfigsResponse]]: - r"""Return a callable for the list workstation configs method over gRPC. - - Returns all workstation configurations in the - specified cluster. - - Returns: - Callable[[~.ListWorkstationConfigsRequest], - Awaitable[~.ListWorkstationConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_configs' not in self._stubs: - self._stubs['list_workstation_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListWorkstationConfigs', - request_serializer=workstations.ListWorkstationConfigsRequest.serialize, - response_deserializer=workstations.ListWorkstationConfigsResponse.deserialize, - ) - return self._stubs['list_workstation_configs'] - - @property - def list_usable_workstation_configs(self) -> Callable[ - [workstations.ListUsableWorkstationConfigsRequest], - Awaitable[workstations.ListUsableWorkstationConfigsResponse]]: - r"""Return a callable for the list usable workstation - configs method over gRPC. - - Returns all workstation configurations in the - specified cluster on which the caller has the - "workstations.workstation.create" permission. - - Returns: - Callable[[~.ListUsableWorkstationConfigsRequest], - Awaitable[~.ListUsableWorkstationConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_usable_workstation_configs' not in self._stubs: - self._stubs['list_usable_workstation_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListUsableWorkstationConfigs', - request_serializer=workstations.ListUsableWorkstationConfigsRequest.serialize, - response_deserializer=workstations.ListUsableWorkstationConfigsResponse.deserialize, - ) - return self._stubs['list_usable_workstation_configs'] - - @property - def create_workstation_config(self) -> Callable[ - [workstations.CreateWorkstationConfigRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create workstation config method over gRPC. - - Creates a new workstation configuration. - - Returns: - Callable[[~.CreateWorkstationConfigRequest], - 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_workstation_config' not in self._stubs: - self._stubs['create_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/CreateWorkstationConfig', - request_serializer=workstations.CreateWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation_config'] - - @property - def update_workstation_config(self) -> Callable[ - [workstations.UpdateWorkstationConfigRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update workstation config method over gRPC. - - Updates an existing workstation configuration. - - Returns: - Callable[[~.UpdateWorkstationConfigRequest], - 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_workstation_config' not in self._stubs: - self._stubs['update_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/UpdateWorkstationConfig', - request_serializer=workstations.UpdateWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation_config'] - - @property - def delete_workstation_config(self) -> Callable[ - [workstations.DeleteWorkstationConfigRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete workstation config method over gRPC. - - Deletes the specified workstation configuration. - - Returns: - Callable[[~.DeleteWorkstationConfigRequest], - 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_workstation_config' not in self._stubs: - self._stubs['delete_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/DeleteWorkstationConfig', - request_serializer=workstations.DeleteWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation_config'] - - @property - def get_workstation(self) -> Callable[ - [workstations.GetWorkstationRequest], - Awaitable[workstations.Workstation]]: - r"""Return a callable for the get workstation method over gRPC. - - Returns the requested workstation. - - Returns: - Callable[[~.GetWorkstationRequest], - Awaitable[~.Workstation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation' not in self._stubs: - self._stubs['get_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/GetWorkstation', - request_serializer=workstations.GetWorkstationRequest.serialize, - response_deserializer=workstations.Workstation.deserialize, - ) - return self._stubs['get_workstation'] - - @property - def list_workstations(self) -> Callable[ - [workstations.ListWorkstationsRequest], - Awaitable[workstations.ListWorkstationsResponse]]: - r"""Return a callable for the list workstations method over gRPC. - - Returns all Workstations using the specified - workstation configuration. - - Returns: - Callable[[~.ListWorkstationsRequest], - Awaitable[~.ListWorkstationsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstations' not in self._stubs: - self._stubs['list_workstations'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListWorkstations', - request_serializer=workstations.ListWorkstationsRequest.serialize, - response_deserializer=workstations.ListWorkstationsResponse.deserialize, - ) - return self._stubs['list_workstations'] - - @property - def list_usable_workstations(self) -> Callable[ - [workstations.ListUsableWorkstationsRequest], - Awaitable[workstations.ListUsableWorkstationsResponse]]: - r"""Return a callable for the list usable workstations method over gRPC. - - Returns all workstations using the specified - workstation configuration on which the caller has the - "workstations.workstations.use" permission. - - Returns: - Callable[[~.ListUsableWorkstationsRequest], - Awaitable[~.ListUsableWorkstationsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_usable_workstations' not in self._stubs: - self._stubs['list_usable_workstations'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/ListUsableWorkstations', - request_serializer=workstations.ListUsableWorkstationsRequest.serialize, - response_deserializer=workstations.ListUsableWorkstationsResponse.deserialize, - ) - return self._stubs['list_usable_workstations'] - - @property - def create_workstation(self) -> Callable[ - [workstations.CreateWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create workstation method over gRPC. - - Creates a new workstation. - - Returns: - Callable[[~.CreateWorkstationRequest], - 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_workstation' not in self._stubs: - self._stubs['create_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/CreateWorkstation', - request_serializer=workstations.CreateWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation'] - - @property - def update_workstation(self) -> Callable[ - [workstations.UpdateWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update workstation method over gRPC. - - Updates an existing workstation. - - Returns: - Callable[[~.UpdateWorkstationRequest], - 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_workstation' not in self._stubs: - self._stubs['update_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/UpdateWorkstation', - request_serializer=workstations.UpdateWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation'] - - @property - def delete_workstation(self) -> Callable[ - [workstations.DeleteWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete workstation method over gRPC. - - Deletes the specified workstation. - - Returns: - Callable[[~.DeleteWorkstationRequest], - 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_workstation' not in self._stubs: - self._stubs['delete_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/DeleteWorkstation', - request_serializer=workstations.DeleteWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation'] - - @property - def start_workstation(self) -> Callable[ - [workstations.StartWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the start workstation method over gRPC. - - Starts running a workstation so that users can - connect to it. - - Returns: - Callable[[~.StartWorkstationRequest], - 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 'start_workstation' not in self._stubs: - self._stubs['start_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/StartWorkstation', - request_serializer=workstations.StartWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['start_workstation'] - - @property - def stop_workstation(self) -> Callable[ - [workstations.StopWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the stop workstation method over gRPC. - - Stops running a workstation, reducing costs. - - Returns: - Callable[[~.StopWorkstationRequest], - 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 'stop_workstation' not in self._stubs: - self._stubs['stop_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/StopWorkstation', - request_serializer=workstations.StopWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['stop_workstation'] - - @property - def generate_access_token(self) -> Callable[ - [workstations.GenerateAccessTokenRequest], - Awaitable[workstations.GenerateAccessTokenResponse]]: - r"""Return a callable for the generate access token method over gRPC. - - Returns a short-lived credential that can be used to - send authenticated and authorized traffic to a - workstation. - - Returns: - Callable[[~.GenerateAccessTokenRequest], - Awaitable[~.GenerateAccessTokenResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_access_token' not in self._stubs: - self._stubs['generate_access_token'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1.Workstations/GenerateAccessToken', - request_serializer=workstations.GenerateAccessTokenRequest.serialize, - response_deserializer=workstations.GenerateAccessTokenResponse.deserialize, - ) - return self._stubs['generate_access_token'] - - def close(self): - return self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'WorkstationsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest.py deleted file mode 100644 index 71d5eb89f24b..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/services/workstations/transports/rest.py +++ /dev/null @@ -1,3177 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.workstations_v1.types import workstations -from google.longrunning import operations_pb2 # type: ignore - -from .base import WorkstationsTransport, 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 WorkstationsRestInterceptor: - """Interceptor for Workstations. - - 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 WorkstationsRestTransport. - - .. code-block:: python - class MyCustomWorkstationsInterceptor(WorkstationsRestInterceptor): - def pre_create_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_workstation_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_workstation_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_workstation_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_workstation_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_workstation_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_workstation_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_workstation_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_workstation_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_generate_access_token(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_generate_access_token(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_workstation_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_workstation_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_workstation_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_workstation_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_usable_workstation_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_usable_workstation_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_usable_workstations(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_usable_workstations(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_workstation_clusters(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_workstation_clusters(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_workstation_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_workstation_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_workstations(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_workstations(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_start_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_start_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_stop_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_stop_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_workstation_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_workstation_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_workstation_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_workstation_config(self, response): - logging.log(f"Received response: {response}") - return response - - transport = WorkstationsRestTransport(interceptor=MyCustomWorkstationsInterceptor()) - client = WorkstationsClient(transport=transport) - - - """ - def pre_create_workstation(self, request: workstations.CreateWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_create_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_create_workstation_cluster(self, request: workstations.CreateWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_workstation_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_create_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_workstation_cluster - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_create_workstation_config(self, request: workstations.CreateWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_workstation_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_create_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_workstation_config - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_delete_workstation(self, request: workstations.DeleteWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_delete_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_delete_workstation_cluster(self, request: workstations.DeleteWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_workstation_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_delete_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_workstation_cluster - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_delete_workstation_config(self, request: workstations.DeleteWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_workstation_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_delete_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_workstation_config - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_generate_access_token(self, request: workstations.GenerateAccessTokenRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GenerateAccessTokenRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for generate_access_token - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_generate_access_token(self, response: workstations.GenerateAccessTokenResponse) -> workstations.GenerateAccessTokenResponse: - """Post-rpc interceptor for generate_access_token - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_get_workstation(self, request: workstations.GetWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_get_workstation(self, response: workstations.Workstation) -> workstations.Workstation: - """Post-rpc interceptor for get_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_get_workstation_cluster(self, request: workstations.GetWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_workstation_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_get_workstation_cluster(self, response: workstations.WorkstationCluster) -> workstations.WorkstationCluster: - """Post-rpc interceptor for get_workstation_cluster - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_get_workstation_config(self, request: workstations.GetWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_workstation_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_get_workstation_config(self, response: workstations.WorkstationConfig) -> workstations.WorkstationConfig: - """Post-rpc interceptor for get_workstation_config - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_list_usable_workstation_configs(self, request: workstations.ListUsableWorkstationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListUsableWorkstationConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_usable_workstation_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_usable_workstation_configs(self, response: workstations.ListUsableWorkstationConfigsResponse) -> workstations.ListUsableWorkstationConfigsResponse: - """Post-rpc interceptor for list_usable_workstation_configs - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_list_usable_workstations(self, request: workstations.ListUsableWorkstationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListUsableWorkstationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_usable_workstations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_usable_workstations(self, response: workstations.ListUsableWorkstationsResponse) -> workstations.ListUsableWorkstationsResponse: - """Post-rpc interceptor for list_usable_workstations - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_list_workstation_clusters(self, request: workstations.ListWorkstationClustersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationClustersRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_workstation_clusters - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_workstation_clusters(self, response: workstations.ListWorkstationClustersResponse) -> workstations.ListWorkstationClustersResponse: - """Post-rpc interceptor for list_workstation_clusters - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_list_workstation_configs(self, request: workstations.ListWorkstationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_workstation_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_workstation_configs(self, response: workstations.ListWorkstationConfigsResponse) -> workstations.ListWorkstationConfigsResponse: - """Post-rpc interceptor for list_workstation_configs - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_list_workstations(self, request: workstations.ListWorkstationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_workstations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_workstations(self, response: workstations.ListWorkstationsResponse) -> workstations.ListWorkstationsResponse: - """Post-rpc interceptor for list_workstations - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_start_workstation(self, request: workstations.StartWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.StartWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for start_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_start_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for start_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_stop_workstation(self, request: workstations.StopWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.StopWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for stop_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_stop_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for stop_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_update_workstation(self, request: workstations.UpdateWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_update_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_update_workstation_cluster(self, request: workstations.UpdateWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_workstation_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_update_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_workstation_cluster - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_update_workstation_config(self, request: workstations.UpdateWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_workstation_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_update_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_workstation_config - - Override in a subclass to manipulate the response - after it is returned by the Workstations 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 Workstations 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 Workstations 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 Workstations 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 Workstations 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 Workstations 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 Workstations server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_delete_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for delete_operation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class WorkstationsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: WorkstationsRestInterceptor - - -class WorkstationsRestTransport(WorkstationsTransport): - """REST backend transport for Workstations. - - Service for interacting with Cloud Workstations. - - 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 = 'workstations.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[WorkstationsRestInterceptor] = 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 WorkstationsRestInterceptor() - 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.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateWorkstation(WorkstationsRestStub): - def __hash__(self): - return hash("CreateWorkstation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "workstationId" : "", } - - @classmethod - def _get_unset_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: workstations.CreateWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create workstation method over HTTP. - - Args: - request (~.workstations.CreateWorkstationRequest): - The request object. Message for creating a - CreateWorkstation. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations', - 'body': 'workstation', - }, - ] - request, metadata = self._interceptor.pre_create_workstation(request, metadata) - pb_request = workstations.CreateWorkstationRequest.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_workstation(resp) - return resp - - class _CreateWorkstationCluster(WorkstationsRestStub): - def __hash__(self): - return hash("CreateWorkstationCluster") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "workstationClusterId" : "", } - - @classmethod - def _get_unset_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: workstations.CreateWorkstationClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create workstation - cluster method over HTTP. - - Args: - request (~.workstations.CreateWorkstationClusterRequest): - The request object. Message for creating a - CreateWorkstationCluster. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/workstationClusters', - 'body': 'workstation_cluster', - }, - ] - request, metadata = self._interceptor.pre_create_workstation_cluster(request, metadata) - pb_request = workstations.CreateWorkstationClusterRequest.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_workstation_cluster(resp) - return resp - - class _CreateWorkstationConfig(WorkstationsRestStub): - def __hash__(self): - return hash("CreateWorkstationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "workstationConfigId" : "", } - - @classmethod - def _get_unset_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: workstations.CreateWorkstationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create workstation config method over HTTP. - - Args: - request (~.workstations.CreateWorkstationConfigRequest): - The request object. Message for creating a - CreateWorkstationConfig. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs', - 'body': 'workstation_config', - }, - ] - request, metadata = self._interceptor.pre_create_workstation_config(request, metadata) - pb_request = workstations.CreateWorkstationConfigRequest.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_workstation_config(resp) - return resp - - class _DeleteWorkstation(WorkstationsRestStub): - def __hash__(self): - return hash("DeleteWorkstation") - - __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: workstations.DeleteWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete workstation method over HTTP. - - Args: - request (~.workstations.DeleteWorkstationRequest): - The request object. Request message for - DeleteWorkstation. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_workstation(request, metadata) - pb_request = workstations.DeleteWorkstationRequest.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_workstation(resp) - return resp - - class _DeleteWorkstationCluster(WorkstationsRestStub): - def __hash__(self): - return hash("DeleteWorkstationCluster") - - __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: workstations.DeleteWorkstationClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete workstation - cluster method over HTTP. - - Args: - request (~.workstations.DeleteWorkstationClusterRequest): - The request object. Message for deleting a workstation - cluster. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_workstation_cluster(request, metadata) - pb_request = workstations.DeleteWorkstationClusterRequest.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_workstation_cluster(resp) - return resp - - class _DeleteWorkstationConfig(WorkstationsRestStub): - def __hash__(self): - return hash("DeleteWorkstationConfig") - - __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: workstations.DeleteWorkstationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete workstation config method over HTTP. - - Args: - request (~.workstations.DeleteWorkstationConfigRequest): - The request object. Message for deleting a workstation - configuration. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_workstation_config(request, metadata) - pb_request = workstations.DeleteWorkstationConfigRequest.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_workstation_config(resp) - return resp - - class _GenerateAccessToken(WorkstationsRestStub): - def __hash__(self): - return hash("GenerateAccessToken") - - __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: workstations.GenerateAccessTokenRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.GenerateAccessTokenResponse: - r"""Call the generate access token method over HTTP. - - Args: - request (~.workstations.GenerateAccessTokenRequest): - The request object. Request message for - GenerateAccessToken. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.workstations.GenerateAccessTokenResponse: - Response message for - GenerateAccessToken. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{workstation=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:generateAccessToken', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_generate_access_token(request, metadata) - pb_request = workstations.GenerateAccessTokenRequest.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 = workstations.GenerateAccessTokenResponse() - pb_resp = workstations.GenerateAccessTokenResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_generate_access_token(resp) - return resp - - class _GetWorkstation(WorkstationsRestStub): - def __hash__(self): - return hash("GetWorkstation") - - __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: workstations.GetWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.Workstation: - r"""Call the get workstation method over HTTP. - - Args: - request (~.workstations.GetWorkstationRequest): - The request object. Request message for GetWorkstation. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.workstations.Workstation: - A single instance of a developer - workstation with its own persistent - storage. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', - }, - ] - request, metadata = self._interceptor.pre_get_workstation(request, metadata) - pb_request = workstations.GetWorkstationRequest.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 = workstations.Workstation() - pb_resp = workstations.Workstation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_workstation(resp) - return resp - - class _GetWorkstationCluster(WorkstationsRestStub): - def __hash__(self): - return hash("GetWorkstationCluster") - - __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: workstations.GetWorkstationClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.WorkstationCluster: - r"""Call the get workstation cluster method over HTTP. - - Args: - request (~.workstations.GetWorkstationClusterRequest): - The request object. Request message for - GetWorkstationCluster. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.workstations.WorkstationCluster: - A grouping of workstation - configurations and the associated - workstations in that region. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*}', - }, - ] - request, metadata = self._interceptor.pre_get_workstation_cluster(request, metadata) - pb_request = workstations.GetWorkstationClusterRequest.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 = workstations.WorkstationCluster() - pb_resp = workstations.WorkstationCluster.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_workstation_cluster(resp) - return resp - - class _GetWorkstationConfig(WorkstationsRestStub): - def __hash__(self): - return hash("GetWorkstationConfig") - - __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: workstations.GetWorkstationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.WorkstationConfig: - r"""Call the get workstation config method over HTTP. - - Args: - request (~.workstations.GetWorkstationConfigRequest): - The request object. Request message for - GetWorkstationConfig. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.workstations.WorkstationConfig: - A set of configuration options - describing how a workstation will be - run. Workstation configurations are - intended to be shared across multiple - workstations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_get_workstation_config(request, metadata) - pb_request = workstations.GetWorkstationConfigRequest.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 = workstations.WorkstationConfig() - pb_resp = workstations.WorkstationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_workstation_config(resp) - return resp - - class _ListUsableWorkstationConfigs(WorkstationsRestStub): - def __hash__(self): - return hash("ListUsableWorkstationConfigs") - - __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: workstations.ListUsableWorkstationConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListUsableWorkstationConfigsResponse: - r"""Call the list usable workstation - configs method over HTTP. - - Args: - request (~.workstations.ListUsableWorkstationConfigsRequest): - The request object. Request message for - ListUsableWorkstationConfigs. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.workstations.ListUsableWorkstationConfigsResponse: - Response message for - ListUsableWorkstationConfigs. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs:listUsable', - }, - ] - request, metadata = self._interceptor.pre_list_usable_workstation_configs(request, metadata) - pb_request = workstations.ListUsableWorkstationConfigsRequest.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 = workstations.ListUsableWorkstationConfigsResponse() - pb_resp = workstations.ListUsableWorkstationConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_usable_workstation_configs(resp) - return resp - - class _ListUsableWorkstations(WorkstationsRestStub): - def __hash__(self): - return hash("ListUsableWorkstations") - - __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: workstations.ListUsableWorkstationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListUsableWorkstationsResponse: - r"""Call the list usable workstations method over HTTP. - - Args: - request (~.workstations.ListUsableWorkstationsRequest): - The request object. Request message for - ListUsableWorkstations. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.workstations.ListUsableWorkstationsResponse: - Response message for - ListUsableWorkstations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations:listUsable', - }, - ] - request, metadata = self._interceptor.pre_list_usable_workstations(request, metadata) - pb_request = workstations.ListUsableWorkstationsRequest.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 = workstations.ListUsableWorkstationsResponse() - pb_resp = workstations.ListUsableWorkstationsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_usable_workstations(resp) - return resp - - class _ListWorkstationClusters(WorkstationsRestStub): - def __hash__(self): - return hash("ListWorkstationClusters") - - __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: workstations.ListWorkstationClustersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListWorkstationClustersResponse: - r"""Call the list workstation clusters method over HTTP. - - Args: - request (~.workstations.ListWorkstationClustersRequest): - The request object. Request message for - ListWorkstationClusters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.workstations.ListWorkstationClustersResponse: - Response message for - ListWorkstationClusters. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/workstationClusters', - }, - ] - request, metadata = self._interceptor.pre_list_workstation_clusters(request, metadata) - pb_request = workstations.ListWorkstationClustersRequest.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 = workstations.ListWorkstationClustersResponse() - pb_resp = workstations.ListWorkstationClustersResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_workstation_clusters(resp) - return resp - - class _ListWorkstationConfigs(WorkstationsRestStub): - def __hash__(self): - return hash("ListWorkstationConfigs") - - __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: workstations.ListWorkstationConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListWorkstationConfigsResponse: - r"""Call the list workstation configs method over HTTP. - - Args: - request (~.workstations.ListWorkstationConfigsRequest): - The request object. Request message for - ListWorkstationConfigs. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.workstations.ListWorkstationConfigsResponse: - Response message for - ListWorkstationConfigs. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs', - }, - ] - request, metadata = self._interceptor.pre_list_workstation_configs(request, metadata) - pb_request = workstations.ListWorkstationConfigsRequest.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 = workstations.ListWorkstationConfigsResponse() - pb_resp = workstations.ListWorkstationConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_workstation_configs(resp) - return resp - - class _ListWorkstations(WorkstationsRestStub): - def __hash__(self): - return hash("ListWorkstations") - - __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: workstations.ListWorkstationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListWorkstationsResponse: - r"""Call the list workstations method over HTTP. - - Args: - request (~.workstations.ListWorkstationsRequest): - The request object. Request message for ListWorkstations. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.workstations.ListWorkstationsResponse: - Response message for - ListWorkstations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations', - }, - ] - request, metadata = self._interceptor.pre_list_workstations(request, metadata) - pb_request = workstations.ListWorkstationsRequest.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 = workstations.ListWorkstationsResponse() - pb_resp = workstations.ListWorkstationsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_workstations(resp) - return resp - - class _StartWorkstation(WorkstationsRestStub): - def __hash__(self): - return hash("StartWorkstation") - - __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: workstations.StartWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the start workstation method over HTTP. - - Args: - request (~.workstations.StartWorkstationRequest): - The request object. Request message for StartWorkstation. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:start', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_start_workstation(request, metadata) - pb_request = workstations.StartWorkstationRequest.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_start_workstation(resp) - return resp - - class _StopWorkstation(WorkstationsRestStub): - def __hash__(self): - return hash("StopWorkstation") - - __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: workstations.StopWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the stop workstation method over HTTP. - - Args: - request (~.workstations.StopWorkstationRequest): - The request object. Request message for StopWorkstation. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:stop', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_stop_workstation(request, metadata) - pb_request = workstations.StopWorkstationRequest.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_stop_workstation(resp) - return resp - - class _UpdateWorkstation(WorkstationsRestStub): - def __hash__(self): - return hash("UpdateWorkstation") - - __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: workstations.UpdateWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update workstation method over HTTP. - - Args: - request (~.workstations.UpdateWorkstationRequest): - The request object. Request message for - UpdateWorkstation. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{workstation.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', - 'body': 'workstation', - }, - ] - request, metadata = self._interceptor.pre_update_workstation(request, metadata) - pb_request = workstations.UpdateWorkstationRequest.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_workstation(resp) - return resp - - class _UpdateWorkstationCluster(WorkstationsRestStub): - def __hash__(self): - return hash("UpdateWorkstationCluster") - - __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: workstations.UpdateWorkstationClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update workstation - cluster method over HTTP. - - Args: - request (~.workstations.UpdateWorkstationClusterRequest): - The request object. Request message for - UpdateWorkstationCluster. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{workstation_cluster.name=projects/*/locations/*/workstationClusters/*}', - 'body': 'workstation_cluster', - }, - ] - request, metadata = self._interceptor.pre_update_workstation_cluster(request, metadata) - pb_request = workstations.UpdateWorkstationClusterRequest.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_workstation_cluster(resp) - return resp - - class _UpdateWorkstationConfig(WorkstationsRestStub): - def __hash__(self): - return hash("UpdateWorkstationConfig") - - __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: workstations.UpdateWorkstationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update workstation config method over HTTP. - - Args: - request (~.workstations.UpdateWorkstationConfigRequest): - The request object. Request message for - UpdateWorkstationConfig. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{workstation_config.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', - 'body': 'workstation_config', - }, - ] - request, metadata = self._interceptor.pre_update_workstation_config(request, metadata) - pb_request = workstations.UpdateWorkstationConfigRequest.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_workstation_config(resp) - return resp - - @property - def create_workstation(self) -> Callable[ - [workstations.CreateWorkstationRequest], - 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._CreateWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_workstation_cluster(self) -> Callable[ - [workstations.CreateWorkstationClusterRequest], - 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._CreateWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_workstation_config(self) -> Callable[ - [workstations.CreateWorkstationConfigRequest], - 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._CreateWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_workstation(self) -> Callable[ - [workstations.DeleteWorkstationRequest], - 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._DeleteWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_workstation_cluster(self) -> Callable[ - [workstations.DeleteWorkstationClusterRequest], - 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._DeleteWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_workstation_config(self) -> Callable[ - [workstations.DeleteWorkstationConfigRequest], - 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._DeleteWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def generate_access_token(self) -> Callable[ - [workstations.GenerateAccessTokenRequest], - workstations.GenerateAccessTokenResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GenerateAccessToken(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_workstation(self) -> Callable[ - [workstations.GetWorkstationRequest], - workstations.Workstation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_workstation_cluster(self) -> Callable[ - [workstations.GetWorkstationClusterRequest], - workstations.WorkstationCluster]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_workstation_config(self) -> Callable[ - [workstations.GetWorkstationConfigRequest], - workstations.WorkstationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_usable_workstation_configs(self) -> Callable[ - [workstations.ListUsableWorkstationConfigsRequest], - workstations.ListUsableWorkstationConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListUsableWorkstationConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_usable_workstations(self) -> Callable[ - [workstations.ListUsableWorkstationsRequest], - workstations.ListUsableWorkstationsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListUsableWorkstations(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_workstation_clusters(self) -> Callable[ - [workstations.ListWorkstationClustersRequest], - workstations.ListWorkstationClustersResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListWorkstationClusters(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_workstation_configs(self) -> Callable[ - [workstations.ListWorkstationConfigsRequest], - workstations.ListWorkstationConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListWorkstationConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_workstations(self) -> Callable[ - [workstations.ListWorkstationsRequest], - workstations.ListWorkstationsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListWorkstations(self._session, self._host, self._interceptor) # type: ignore - - @property - def start_workstation(self) -> Callable[ - [workstations.StartWorkstationRequest], - 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._StartWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def stop_workstation(self) -> Callable[ - [workstations.StopWorkstationRequest], - 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._StopWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_workstation(self) -> Callable[ - [workstations.UpdateWorkstationRequest], - 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._UpdateWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_workstation_cluster(self) -> Callable[ - [workstations.UpdateWorkstationClusterRequest], - 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._UpdateWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_workstation_config(self) -> Callable[ - [workstations.UpdateWorkstationConfigRequest], - 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._UpdateWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(WorkstationsRestStub): - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:getIamPolicy', - }, - ] - - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(WorkstationsRestStub): - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:setIamPolicy', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - 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) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(WorkstationsRestStub): - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:testIamPermissions', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - 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) - - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(WorkstationsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - 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 self._interceptor.post_cancel_operation(None) - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(WorkstationsRestStub): - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object for DeleteOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_delete_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(WorkstationsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(WorkstationsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'WorkstationsRestTransport', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/__init__.py deleted file mode 100644 index 78e68e36bfd4..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/__init__.py +++ /dev/null @@ -1,80 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .workstations import ( - CreateWorkstationClusterRequest, - CreateWorkstationConfigRequest, - CreateWorkstationRequest, - DeleteWorkstationClusterRequest, - DeleteWorkstationConfigRequest, - DeleteWorkstationRequest, - GenerateAccessTokenRequest, - GenerateAccessTokenResponse, - GetWorkstationClusterRequest, - GetWorkstationConfigRequest, - GetWorkstationRequest, - ListUsableWorkstationConfigsRequest, - ListUsableWorkstationConfigsResponse, - ListUsableWorkstationsRequest, - ListUsableWorkstationsResponse, - ListWorkstationClustersRequest, - ListWorkstationClustersResponse, - ListWorkstationConfigsRequest, - ListWorkstationConfigsResponse, - ListWorkstationsRequest, - ListWorkstationsResponse, - OperationMetadata, - StartWorkstationRequest, - StopWorkstationRequest, - UpdateWorkstationClusterRequest, - UpdateWorkstationConfigRequest, - UpdateWorkstationRequest, - Workstation, - WorkstationCluster, - WorkstationConfig, -) - -__all__ = ( - 'CreateWorkstationClusterRequest', - 'CreateWorkstationConfigRequest', - 'CreateWorkstationRequest', - 'DeleteWorkstationClusterRequest', - 'DeleteWorkstationConfigRequest', - 'DeleteWorkstationRequest', - 'GenerateAccessTokenRequest', - 'GenerateAccessTokenResponse', - 'GetWorkstationClusterRequest', - 'GetWorkstationConfigRequest', - 'GetWorkstationRequest', - 'ListUsableWorkstationConfigsRequest', - 'ListUsableWorkstationConfigsResponse', - 'ListUsableWorkstationsRequest', - 'ListUsableWorkstationsResponse', - 'ListWorkstationClustersRequest', - 'ListWorkstationClustersResponse', - 'ListWorkstationConfigsRequest', - 'ListWorkstationConfigsResponse', - 'ListWorkstationsRequest', - 'ListWorkstationsResponse', - 'OperationMetadata', - 'StartWorkstationRequest', - 'StopWorkstationRequest', - 'UpdateWorkstationClusterRequest', - 'UpdateWorkstationConfigRequest', - 'UpdateWorkstationRequest', - 'Workstation', - 'WorkstationCluster', - 'WorkstationConfig', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/workstations.py b/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/workstations.py deleted file mode 100644 index b82525ca4459..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/google/cloud/workstations_v1/types/workstations.py +++ /dev/null @@ -1,1722 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.workstations.v1', - manifest={ - 'WorkstationCluster', - 'WorkstationConfig', - 'Workstation', - 'GetWorkstationClusterRequest', - 'ListWorkstationClustersRequest', - 'ListWorkstationClustersResponse', - 'CreateWorkstationClusterRequest', - 'UpdateWorkstationClusterRequest', - 'DeleteWorkstationClusterRequest', - 'GetWorkstationConfigRequest', - 'ListWorkstationConfigsRequest', - 'ListWorkstationConfigsResponse', - 'ListUsableWorkstationConfigsRequest', - 'ListUsableWorkstationConfigsResponse', - 'CreateWorkstationConfigRequest', - 'UpdateWorkstationConfigRequest', - 'DeleteWorkstationConfigRequest', - 'GetWorkstationRequest', - 'ListWorkstationsRequest', - 'ListWorkstationsResponse', - 'ListUsableWorkstationsRequest', - 'ListUsableWorkstationsResponse', - 'CreateWorkstationRequest', - 'UpdateWorkstationRequest', - 'DeleteWorkstationRequest', - 'StartWorkstationRequest', - 'StopWorkstationRequest', - 'GenerateAccessTokenRequest', - 'GenerateAccessTokenResponse', - 'OperationMetadata', - }, -) - - -class WorkstationCluster(proto.Message): - r"""A grouping of workstation configurations and the associated - workstations in that region. - - Attributes: - name (str): - Full name of this resource. - display_name (str): - Human-readable name for this resource. - uid (str): - Output only. A system-assigned unique - identified for this resource. - reconciling (bool): - Output only. Indicates whether this resource - is currently being updated to match its intended - state. - annotations (MutableMapping[str, str]): - Client-specified annotations. - labels (MutableMapping[str, str]): - Client-specified labels that are applied to - the resource and that are also propagated to the - underlying Compute Engine resources. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this resource was - created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this resource was most - recently updated. - delete_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this resource was - soft-deleted. - etag (str): - Checksum computed by the server. May be sent - on update and delete requests to make sure that - the client has an up-to-date value before - proceeding. - network (str): - Immutable. Name of the Compute Engine network - in which instances associated with this cluster - will be created. - subnetwork (str): - Immutable. Name of the Compute Engine - subnetwork in which instances associated with - this cluster will be created. Must be part of - the subnetwork specified for this cluster. - control_plane_ip (str): - Output only. The private IP address of the - control plane for this cluster. Workstation VMs - need access to this IP address to work with the - service, so make sure that your firewall rules - allow egress from the workstation VMs to this - address. - private_cluster_config (google.cloud.workstations_v1.types.WorkstationCluster.PrivateClusterConfig): - Configuration for private cluster. - degraded (bool): - Output only. Whether this resource is in degraded mode, in - which case it may require user action to restore full - functionality. Details can be found in the ``conditions`` - field. - conditions (MutableSequence[google.rpc.status_pb2.Status]): - Output only. Status conditions describing the - current resource state. - """ - - class PrivateClusterConfig(proto.Message): - r"""Configuration options for private clusters. - - Attributes: - enable_private_endpoint (bool): - Immutable. Whether Workstations endpoint is - private. - cluster_hostname (str): - Output only. Hostname for the workstation - cluster. This field will be populated only when - private endpoint is enabled. To access - workstations in the cluster, create a new DNS - zone mapping this domain name to an internal IP - address and a forwarding rule mapping that - address to the service attachment. - service_attachment_uri (str): - Output only. Service attachment URI for the workstation - cluster. The service attachemnt is created when private - endpoint is enabled. To access workstations in the cluster, - configure access to the managed service using `Private - Service - Connect `__. - allowed_projects (MutableSequence[str]): - Additional projects that are allowed to - attach to the workstation cluster's service - attachment. By default, the workstation - cluster's project and the VPC host project (if - different) are allowed. - """ - - enable_private_endpoint: bool = proto.Field( - proto.BOOL, - number=1, - ) - cluster_hostname: str = proto.Field( - proto.STRING, - number=2, - ) - service_attachment_uri: str = proto.Field( - proto.STRING, - number=3, - ) - allowed_projects: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - uid: str = proto.Field( - proto.STRING, - number=3, - ) - reconciling: bool = proto.Field( - proto.BOOL, - number=4, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=15, - ) - 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, - ) - network: str = proto.Field( - proto.STRING, - number=10, - ) - subnetwork: str = proto.Field( - proto.STRING, - number=11, - ) - control_plane_ip: str = proto.Field( - proto.STRING, - number=16, - ) - private_cluster_config: PrivateClusterConfig = proto.Field( - proto.MESSAGE, - number=12, - message=PrivateClusterConfig, - ) - degraded: bool = proto.Field( - proto.BOOL, - number=13, - ) - conditions: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=status_pb2.Status, - ) - - -class WorkstationConfig(proto.Message): - r"""A set of configuration options describing how a workstation - will be run. Workstation configurations are intended to be - shared across multiple workstations. - - Attributes: - name (str): - Full name of this resource. - display_name (str): - Human-readable name for this resource. - uid (str): - Output only. A system-assigned unique - identified for this resource. - reconciling (bool): - Output only. Indicates whether this resource - is currently being updated to match its intended - state. - annotations (MutableMapping[str, str]): - Client-specified annotations. - labels (MutableMapping[str, str]): - Client-specified labels that are applied to - the resource and that are also propagated to the - underlying Compute Engine resources. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this resource was - created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this resource was most - recently updated. - delete_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this resource was - soft-deleted. - etag (str): - Checksum computed by the server. May be sent - on update and delete requests to make sure that - the client has an up-to-date value before - proceeding. - idle_timeout (google.protobuf.duration_pb2.Duration): - How long to wait before automatically - stopping an instance that hasn't received any - user traffic. A value of 0 indicates that this - instance should never time out due to idleness. - Defaults to 20 minutes. - running_timeout (google.protobuf.duration_pb2.Duration): - How long to wait before automatically stopping a workstation - after it started. A value of 0 indicates that workstations - using this configuration should never time out. Must be - greater than 0 and less than 24 hours if encryption_key is - set. Defaults to 12 hours. - host (google.cloud.workstations_v1.types.WorkstationConfig.Host): - Runtime host for the workstation. - persistent_directories (MutableSequence[google.cloud.workstations_v1.types.WorkstationConfig.PersistentDirectory]): - Directories to persist across workstation - sessions. - container (google.cloud.workstations_v1.types.WorkstationConfig.Container): - Container that will be run for each - workstation using this configuration when that - workstation is started. - encryption_key (google.cloud.workstations_v1.types.WorkstationConfig.CustomerEncryptionKey): - Immutable. Encrypts resources of this - workstation configuration using a - customer-managed encryption key. - If specified, the boot disk of the Compute - Engine instance and the persistent disk are - encrypted using this encryption key. If this - field is not set, the disks are encrypted using - a generated key. Customer-managed encryption - keys do not protect disk metadata. - If the customer-managed encryption key is - rotated, when the workstation instance is - stopped, the system attempts to recreate the - persistent disk with the new version of the key. - Be sure to keep older versions of the key until - the persistent disk is recreated. Otherwise, - data on the persistent disk will be lost. - If the encryption key is revoked, the - workstation session will automatically be - stopped within 7 hours. - - Immutable after the workstation configuration is - created. - degraded (bool): - Output only. Whether this resource is degraded, in which - case it may require user action to restore full - functionality. See also the ``conditions`` field. - conditions (MutableSequence[google.rpc.status_pb2.Status]): - Output only. Status conditions describing the - current resource state. - """ - - class Host(proto.Message): - r"""Runtime host for a workstation. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gce_instance (google.cloud.workstations_v1.types.WorkstationConfig.Host.GceInstance): - Specifies a Compute Engine instance as the - host. - - This field is a member of `oneof`_ ``config``. - """ - - class GceInstance(proto.Message): - r"""A runtime using a Compute Engine instance. - - Attributes: - machine_type (str): - The name of a Compute Engine machine type. - service_account (str): - Email address of the service account used on - VM instances used to support this configuration. - If not set, VMs run with a Google-managed - service account. This service account must have - permission to pull the specified container - image; otherwise, the image must be publicly - accessible. - tags (MutableSequence[str]): - Network tags to add to the Compute Engine - machines backing the Workstations. - pool_size (int): - Number of instances to pool for faster - workstation startup. - pooled_instances (int): - Output only. Number of instances currently - available in the pool for faster workstation - startup. - disable_public_ip_addresses (bool): - Whether instances have no public IP address. - enable_nested_virtualization (bool): - Whether to enable nested virtualization on - instances. - shielded_instance_config (google.cloud.workstations_v1.types.WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig): - A set of Compute Engine Shielded instance - options. - confidential_instance_config (google.cloud.workstations_v1.types.WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig): - A set of Compute Engine Confidential VM - instance options. - boot_disk_size_gb (int): - Size of the boot disk in GB. Defaults to 50. - """ - - class GceShieldedInstanceConfig(proto.Message): - r"""A set of Compute Engine Shielded instance options. - - Attributes: - enable_secure_boot (bool): - Whether the instance has Secure Boot enabled. - enable_vtpm (bool): - Whether the instance has the vTPM enabled. - enable_integrity_monitoring (bool): - Whether the instance has integrity monitoring - enabled. - """ - - enable_secure_boot: bool = proto.Field( - proto.BOOL, - number=1, - ) - enable_vtpm: bool = proto.Field( - proto.BOOL, - number=2, - ) - enable_integrity_monitoring: bool = proto.Field( - proto.BOOL, - number=3, - ) - - class GceConfidentialInstanceConfig(proto.Message): - r"""A set of Compute Engine Confidential VM instance options. - - Attributes: - enable_confidential_compute (bool): - Whether the instance has confidential compute - enabled. - """ - - enable_confidential_compute: bool = proto.Field( - proto.BOOL, - number=1, - ) - - machine_type: str = proto.Field( - proto.STRING, - number=1, - ) - service_account: str = proto.Field( - proto.STRING, - number=2, - ) - tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - pool_size: int = proto.Field( - proto.INT32, - number=5, - ) - pooled_instances: int = proto.Field( - proto.INT32, - number=12, - ) - disable_public_ip_addresses: bool = proto.Field( - proto.BOOL, - number=6, - ) - enable_nested_virtualization: bool = proto.Field( - proto.BOOL, - number=7, - ) - shielded_instance_config: 'WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig' = proto.Field( - proto.MESSAGE, - number=8, - message='WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig', - ) - confidential_instance_config: 'WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig' = proto.Field( - proto.MESSAGE, - number=10, - message='WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig', - ) - boot_disk_size_gb: int = proto.Field( - proto.INT32, - number=9, - ) - - gce_instance: 'WorkstationConfig.Host.GceInstance' = proto.Field( - proto.MESSAGE, - number=1, - oneof='config', - message='WorkstationConfig.Host.GceInstance', - ) - - class PersistentDirectory(proto.Message): - r"""A directory to persist across workstation sessions. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gce_pd (google.cloud.workstations_v1.types.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk): - A PersistentDirectory backed by a Compute - Engine persistent disk. - - This field is a member of `oneof`_ ``directory_type``. - mount_path (str): - Location of this directory in the running - workstation. - """ - - class GceRegionalPersistentDisk(proto.Message): - r"""A PersistentDirectory backed by a Compute Engine regional - persistent disk. - - Attributes: - size_gb (int): - Size of the disk in GB. Must be empty if source_snapshot is - set. Defaults to 200. - fs_type (str): - Type of file system that the disk should be formatted with. - The workstation image must support this file system type. - Must be empty if source_snapshot is set. Defaults to ext4. - disk_type (str): - Type of the disk to use. Defaults to - pd-standard. - source_snapshot (str): - Name of the snapshot to use as the source for the disk. If - set, size_gb and fs_type must be empty. - reclaim_policy (google.cloud.workstations_v1.types.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy): - What should happen to the disk after the - workstation is deleted. Defaults to DELETE. - """ - class ReclaimPolicy(proto.Enum): - r"""Value representing what should happen to the disk after the - workstation is deleted. - - Values: - RECLAIM_POLICY_UNSPECIFIED (0): - Do not use. - DELETE (1): - The persistent disk will be deleted with the - workstation. - RETAIN (2): - The persistent disk will be remain after the - workstation is deleted, and the administrator - must manually delete the disk. - """ - RECLAIM_POLICY_UNSPECIFIED = 0 - DELETE = 1 - RETAIN = 2 - - size_gb: int = proto.Field( - proto.INT32, - number=1, - ) - fs_type: str = proto.Field( - proto.STRING, - number=2, - ) - disk_type: str = proto.Field( - proto.STRING, - number=3, - ) - source_snapshot: str = proto.Field( - proto.STRING, - number=5, - ) - reclaim_policy: 'WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy' = proto.Field( - proto.ENUM, - number=4, - enum='WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy', - ) - - gce_pd: 'WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk' = proto.Field( - proto.MESSAGE, - number=2, - oneof='directory_type', - message='WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk', - ) - mount_path: str = proto.Field( - proto.STRING, - number=1, - ) - - class Container(proto.Message): - r"""A Docker container. - - Attributes: - image (str): - Docker image defining the container. This - image must be accessible by the service account - specified in the workstation configuration. - command (MutableSequence[str]): - If set, overrides the default ENTRYPOINT - specified by the image. - args (MutableSequence[str]): - Arguments passed to the entrypoint. - env (MutableMapping[str, str]): - Environment variables passed to the - container's entrypoint. - working_dir (str): - If set, overrides the default DIR specified - by the image. - run_as_user (int): - If set, overrides the USER specified in the - image with the given uid. - """ - - image: str = proto.Field( - proto.STRING, - number=1, - ) - command: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - args: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - env: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - working_dir: str = proto.Field( - proto.STRING, - number=5, - ) - run_as_user: int = proto.Field( - proto.INT32, - number=6, - ) - - class CustomerEncryptionKey(proto.Message): - r"""A customer-managed encryption key for the Compute Engine - resources of this workstation configuration. - - Attributes: - kms_key (str): - Immutable. The name of the Google Cloud KMS encryption key. - For example, - ``projects/PROJECT_ID/locations/REGION/keyRings/KEY_RING/cryptoKeys/KEY_NAME``. - kms_key_service_account (str): - Immutable. The service account to use with the specified KMS - key. We recommend that you use a separate service account - and follow KMS best practices. For more information, see - `Separation of - duties `__ - and ``gcloud kms keys add-iam-policy-binding`` - ```--member`` `__. - """ - - kms_key: str = proto.Field( - proto.STRING, - number=1, - ) - kms_key_service_account: str = proto.Field( - proto.STRING, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - uid: str = proto.Field( - proto.STRING, - number=3, - ) - reconciling: bool = proto.Field( - proto.BOOL, - number=4, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=18, - ) - 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, - ) - idle_timeout: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=10, - message=duration_pb2.Duration, - ) - running_timeout: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=11, - message=duration_pb2.Duration, - ) - host: Host = proto.Field( - proto.MESSAGE, - number=12, - message=Host, - ) - persistent_directories: MutableSequence[PersistentDirectory] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message=PersistentDirectory, - ) - container: Container = proto.Field( - proto.MESSAGE, - number=14, - message=Container, - ) - encryption_key: CustomerEncryptionKey = proto.Field( - proto.MESSAGE, - number=17, - message=CustomerEncryptionKey, - ) - degraded: bool = proto.Field( - proto.BOOL, - number=15, - ) - conditions: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=16, - message=status_pb2.Status, - ) - - -class Workstation(proto.Message): - r"""A single instance of a developer workstation with its own - persistent storage. - - Attributes: - name (str): - Full name of this resource. - display_name (str): - Human-readable name for this resource. - uid (str): - Output only. A system-assigned unique - identified for this resource. - reconciling (bool): - Output only. Indicates whether this resource - is currently being updated to match its intended - state. - annotations (MutableMapping[str, str]): - Client-specified annotations. - labels (MutableMapping[str, str]): - Client-specified labels that are applied to - the resource and that are also propagated to the - underlying Compute Engine resources. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this resource was - created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this resource was most - recently updated. - delete_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this resource was - soft-deleted. - etag (str): - Checksum computed by the server. May be sent - on update and delete requests to make sure that - the client has an up-to-date value before - proceeding. - state (google.cloud.workstations_v1.types.Workstation.State): - Output only. Current state of the - workstation. - host (str): - Output only. Host to which clients can send HTTPS traffic - that will be received by the workstation. Authorized traffic - will be received to the workstation as HTTP on port 80. To - send traffic to a different port, clients may prefix the - host with the destination port in the format - ``{port}-{host}``. - """ - class State(proto.Enum): - r"""Whether a workstation is running and ready to receive user - requests. - - Values: - STATE_UNSPECIFIED (0): - Do not use. - STATE_STARTING (1): - The workstation is not yet ready to accept - requests from users but will be soon. - STATE_RUNNING (2): - The workstation is ready to accept requests - from users. - STATE_STOPPING (3): - The workstation is being stopped. - STATE_STOPPED (4): - The workstation is stopped and will not be - able to receive requests until it is started. - """ - STATE_UNSPECIFIED = 0 - STATE_STARTING = 1 - STATE_RUNNING = 2 - STATE_STOPPING = 3 - STATE_STOPPED = 4 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - uid: str = proto.Field( - proto.STRING, - number=3, - ) - reconciling: bool = proto.Field( - proto.BOOL, - number=4, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=13, - ) - 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, - ) - state: State = proto.Field( - proto.ENUM, - number=10, - enum=State, - ) - host: str = proto.Field( - proto.STRING, - number=11, - ) - - -class GetWorkstationClusterRequest(proto.Message): - r"""Request message for GetWorkstationCluster. - - Attributes: - name (str): - Required. Name of the requested resource. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListWorkstationClustersRequest(proto.Message): - r"""Request message for ListWorkstationClusters. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Maximum number of items to return. - page_token (str): - next_page_token value returned from a previous List request, - if any. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListWorkstationClustersResponse(proto.Message): - r"""Response message for ListWorkstationClusters. - - Attributes: - workstation_clusters (MutableSequence[google.cloud.workstations_v1.types.WorkstationCluster]): - The requested workstation clusters. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstation_clusters: MutableSequence['WorkstationCluster'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='WorkstationCluster', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateWorkstationClusterRequest(proto.Message): - r"""Message for creating a CreateWorkstationCluster. - - Attributes: - parent (str): - Required. Parent resource name. - workstation_cluster_id (str): - Required. ID to use for the workstation - cluster. - workstation_cluster (google.cloud.workstations_v1.types.WorkstationCluster): - Required. Workstation cluster to create. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - workstation_cluster_id: str = proto.Field( - proto.STRING, - number=2, - ) - workstation_cluster: 'WorkstationCluster' = proto.Field( - proto.MESSAGE, - number=3, - message='WorkstationCluster', - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateWorkstationClusterRequest(proto.Message): - r"""Request message for UpdateWorkstationCluster. - - Attributes: - workstation_cluster (google.cloud.workstations_v1.types.WorkstationCluster): - Required. Workstation cluster to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask that specifies which fields in - the workstation cluster should be updated. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - allow_missing (bool): - If set, and the workstation cluster is not found, a new - workstation cluster will be created. In this situation, - update_mask is ignored. - """ - - workstation_cluster: 'WorkstationCluster' = proto.Field( - proto.MESSAGE, - number=1, - message='WorkstationCluster', - ) - 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, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class DeleteWorkstationClusterRequest(proto.Message): - r"""Message for deleting a workstation cluster. - - Attributes: - name (str): - Required. Name of the workstation cluster to - delete. - validate_only (bool): - If set, validate the request and preview the - review, but do not apply it. - etag (str): - If set, the request will be rejected if the - latest version of the workstation cluster on the - server does not have this ETag. - force (bool): - If set, any workstation configurations and - workstations in the workstation cluster are also - deleted. Otherwise, the request only works if - the workstation cluster has no configurations or - workstations. - """ - - 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, - ) - force: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetWorkstationConfigRequest(proto.Message): - r"""Request message for GetWorkstationConfig. - - Attributes: - name (str): - Required. Name of the requested resource. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListWorkstationConfigsRequest(proto.Message): - r"""Request message for ListWorkstationConfigs. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Maximum number of items to return. - page_token (str): - next_page_token value returned from a previous List request, - if any. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListWorkstationConfigsResponse(proto.Message): - r"""Response message for ListWorkstationConfigs. - - Attributes: - workstation_configs (MutableSequence[google.cloud.workstations_v1.types.WorkstationConfig]): - The requested configs. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstation_configs: MutableSequence['WorkstationConfig'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='WorkstationConfig', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class ListUsableWorkstationConfigsRequest(proto.Message): - r"""Request message for ListUsableWorkstationConfigs. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Maximum number of items to return. - page_token (str): - next_page_token value returned from a previous List request, - if any. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListUsableWorkstationConfigsResponse(proto.Message): - r"""Response message for ListUsableWorkstationConfigs. - - Attributes: - workstation_configs (MutableSequence[google.cloud.workstations_v1.types.WorkstationConfig]): - The requested configs. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstation_configs: MutableSequence['WorkstationConfig'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='WorkstationConfig', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateWorkstationConfigRequest(proto.Message): - r"""Message for creating a CreateWorkstationConfig. - - Attributes: - parent (str): - Required. Parent resource name. - workstation_config_id (str): - Required. ID to use for the workstation - configuration. - workstation_config (google.cloud.workstations_v1.types.WorkstationConfig): - Required. Config to create. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - workstation_config_id: str = proto.Field( - proto.STRING, - number=2, - ) - workstation_config: 'WorkstationConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='WorkstationConfig', - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateWorkstationConfigRequest(proto.Message): - r"""Request message for UpdateWorkstationConfig. - - Attributes: - workstation_config (google.cloud.workstations_v1.types.WorkstationConfig): - Required. Config to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask specifying which fields in the - workstation configuration should be updated. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - allow_missing (bool): - If set and the workstation configuration is not found, a new - workstation configuration will be created. In this - situation, update_mask is ignored. - """ - - workstation_config: 'WorkstationConfig' = proto.Field( - proto.MESSAGE, - number=1, - message='WorkstationConfig', - ) - 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, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class DeleteWorkstationConfigRequest(proto.Message): - r"""Message for deleting a workstation configuration. - - Attributes: - name (str): - Required. Name of the workstation - configuration to delete. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - etag (str): - If set, the request is rejected if the latest - version of the workstation configuration on the - server does not have this ETag. - force (bool): - If set, any workstations in the workstation - configuration are also deleted. Otherwise, the - request works only if the workstation - configuration has no workstations. - """ - - 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, - ) - force: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetWorkstationRequest(proto.Message): - r"""Request message for GetWorkstation. - - Attributes: - name (str): - Required. Name of the requested resource. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListWorkstationsRequest(proto.Message): - r"""Request message for ListWorkstations. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Maximum number of items to return. - page_token (str): - next_page_token value returned from a previous List request, - if any. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListWorkstationsResponse(proto.Message): - r"""Response message for ListWorkstations. - - Attributes: - workstations (MutableSequence[google.cloud.workstations_v1.types.Workstation]): - The requested workstations. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstations: MutableSequence['Workstation'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Workstation', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class ListUsableWorkstationsRequest(proto.Message): - r"""Request message for ListUsableWorkstations. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Maximum number of items to return. - page_token (str): - next_page_token value returned from a previous List request, - if any. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListUsableWorkstationsResponse(proto.Message): - r"""Response message for ListUsableWorkstations. - - Attributes: - workstations (MutableSequence[google.cloud.workstations_v1.types.Workstation]): - The requested workstations. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstations: MutableSequence['Workstation'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Workstation', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateWorkstationRequest(proto.Message): - r"""Message for creating a CreateWorkstation. - - Attributes: - parent (str): - Required. Parent resource name. - workstation_id (str): - Required. ID to use for the workstation. - workstation (google.cloud.workstations_v1.types.Workstation): - Required. Workstation to create. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - workstation_id: str = proto.Field( - proto.STRING, - number=2, - ) - workstation: 'Workstation' = proto.Field( - proto.MESSAGE, - number=3, - message='Workstation', - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateWorkstationRequest(proto.Message): - r"""Request message for UpdateWorkstation. - - Attributes: - workstation (google.cloud.workstations_v1.types.Workstation): - Required. Workstation to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask specifying which fields in the - workstation configuration should be updated. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - allow_missing (bool): - If set and the workstation configuration is not found, a new - workstation configuration is created. In this situation, - update_mask is ignored. - """ - - workstation: 'Workstation' = proto.Field( - proto.MESSAGE, - number=1, - message='Workstation', - ) - 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, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class DeleteWorkstationRequest(proto.Message): - r"""Request message for DeleteWorkstation. - - Attributes: - name (str): - Required. Name of the workstation to delete. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - etag (str): - If set, the request will be rejected if the - latest version of the workstation on the server - does not have this ETag. - """ - - 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 StartWorkstationRequest(proto.Message): - r"""Request message for StartWorkstation. - - Attributes: - name (str): - Required. Name of the workstation to start. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - etag (str): - If set, the request will be rejected if the - latest version of the workstation on the server - does not have this ETag. - """ - - 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 StopWorkstationRequest(proto.Message): - r"""Request message for StopWorkstation. - - Attributes: - name (str): - Required. Name of the workstation to stop. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - etag (str): - If set, the request will be rejected if the - latest version of the workstation on the server - does not have this ETag. - """ - - 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 GenerateAccessTokenRequest(proto.Message): - r"""Request message for GenerateAccessToken. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - expire_time (google.protobuf.timestamp_pb2.Timestamp): - Desired expiration time of the access token. - This value must be at most 24 hours in the - future. If a value is not specified, the token's - expiration time will be set to a default value - of 1 hour in the future. - - This field is a member of `oneof`_ ``expiration``. - ttl (google.protobuf.duration_pb2.Duration): - Desired lifetime duration of the access - token. This value must be at most 24 hours. If a - value is not specified, the token's lifetime - will be set to a default value of 1 hour. - - This field is a member of `oneof`_ ``expiration``. - workstation (str): - Required. Name of the workstation for which - the access token should be generated. - """ - - expire_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - oneof='expiration', - message=timestamp_pb2.Timestamp, - ) - ttl: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - oneof='expiration', - message=duration_pb2.Duration, - ) - workstation: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GenerateAccessTokenResponse(proto.Message): - r"""Response message for GenerateAccessToken. - - Attributes: - access_token (str): - The generated bearer access token. To use this token, - include it in an Authorization header of an HTTP request - sent to the associated workstation's hostname—for example, - ``Authorization: Bearer ``. - expire_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which the generated token will - expire. - """ - - access_token: str = proto.Field( - proto.STRING, - number=1, - ) - expire_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class OperationMetadata(proto.Message): - r"""Metadata for long-running operations. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time that the operation was - created. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time that the operation finished - running. - target (str): - Output only. Server-defined resource path for - the target of the operation. - verb (str): - Output only. Name of the verb executed by the - operation. - status_message (str): - Output only. Human-readable status of the - operation, if any. - requested_cancellation (bool): - Output only. Identifies whether the user has - requested cancellation of the operation. - api_version (str): - Output only. API version used to start the - operation. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - target: str = proto.Field( - proto.STRING, - number=3, - ) - verb: str = proto.Field( - proto.STRING, - number=4, - ) - status_message: str = proto.Field( - proto.STRING, - number=5, - ) - requested_cancellation: bool = proto.Field( - proto.BOOL, - number=6, - ) - api_version: str = proto.Field( - proto.STRING, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-workstations/v1/mypy.ini b/owl-bot-staging/google-cloud-workstations/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-workstations/v1/noxfile.py b/owl-bot-staging/google-cloud-workstations/v1/noxfile.py deleted file mode 100644 index 41a3c4eff40e..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/workstations_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json deleted file mode 100644 index 8dabda2a933a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json +++ /dev/null @@ -1,3307 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.workstations.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-workstations", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.create_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.CreateWorkstationClusterRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation_cluster", - "type": "google.cloud.workstations_v1.types.WorkstationCluster" - }, - { - "name": "workstation_cluster_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_workstation_cluster" - }, - "description": "Sample for CreateWorkstationCluster", - "file": "workstations_v1_generated_workstations_create_workstation_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_CreateWorkstationCluster_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": "workstations_v1_generated_workstations_create_workstation_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.create_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.CreateWorkstationClusterRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation_cluster", - "type": "google.cloud.workstations_v1.types.WorkstationCluster" - }, - { - "name": "workstation_cluster_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_workstation_cluster" - }, - "description": "Sample for CreateWorkstationCluster", - "file": "workstations_v1_generated_workstations_create_workstation_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_CreateWorkstationCluster_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": "workstations_v1_generated_workstations_create_workstation_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.create_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.CreateWorkstationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation_config", - "type": "google.cloud.workstations_v1.types.WorkstationConfig" - }, - { - "name": "workstation_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_workstation_config" - }, - "description": "Sample for CreateWorkstationConfig", - "file": "workstations_v1_generated_workstations_create_workstation_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_CreateWorkstationConfig_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": "workstations_v1_generated_workstations_create_workstation_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.create_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.CreateWorkstationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation_config", - "type": "google.cloud.workstations_v1.types.WorkstationConfig" - }, - { - "name": "workstation_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_workstation_config" - }, - "description": "Sample for CreateWorkstationConfig", - "file": "workstations_v1_generated_workstations_create_workstation_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_CreateWorkstationConfig_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": "workstations_v1_generated_workstations_create_workstation_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.create_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.CreateWorkstationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation", - "type": "google.cloud.workstations_v1.types.Workstation" - }, - { - "name": "workstation_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_workstation" - }, - "description": "Sample for CreateWorkstation", - "file": "workstations_v1_generated_workstations_create_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_CreateWorkstation_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": "workstations_v1_generated_workstations_create_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.create_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.CreateWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.CreateWorkstationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation", - "type": "google.cloud.workstations_v1.types.Workstation" - }, - { - "name": "workstation_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_workstation" - }, - "description": "Sample for CreateWorkstation", - "file": "workstations_v1_generated_workstations_create_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_CreateWorkstation_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": "workstations_v1_generated_workstations_create_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.delete_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.DeleteWorkstationClusterRequest" - }, - { - "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_workstation_cluster" - }, - "description": "Sample for DeleteWorkstationCluster", - "file": "workstations_v1_generated_workstations_delete_workstation_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstationCluster_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": "workstations_v1_generated_workstations_delete_workstation_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.delete_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.DeleteWorkstationClusterRequest" - }, - { - "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_workstation_cluster" - }, - "description": "Sample for DeleteWorkstationCluster", - "file": "workstations_v1_generated_workstations_delete_workstation_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstationCluster_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": "workstations_v1_generated_workstations_delete_workstation_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.delete_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.DeleteWorkstationConfigRequest" - }, - { - "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_workstation_config" - }, - "description": "Sample for DeleteWorkstationConfig", - "file": "workstations_v1_generated_workstations_delete_workstation_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstationConfig_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": "workstations_v1_generated_workstations_delete_workstation_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.delete_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.DeleteWorkstationConfigRequest" - }, - { - "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_workstation_config" - }, - "description": "Sample for DeleteWorkstationConfig", - "file": "workstations_v1_generated_workstations_delete_workstation_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstationConfig_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": "workstations_v1_generated_workstations_delete_workstation_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.delete_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.DeleteWorkstationRequest" - }, - { - "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_workstation" - }, - "description": "Sample for DeleteWorkstation", - "file": "workstations_v1_generated_workstations_delete_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstation_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": "workstations_v1_generated_workstations_delete_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.delete_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.DeleteWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.DeleteWorkstationRequest" - }, - { - "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_workstation" - }, - "description": "Sample for DeleteWorkstation", - "file": "workstations_v1_generated_workstations_delete_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_DeleteWorkstation_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": "workstations_v1_generated_workstations_delete_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.generate_access_token", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.GenerateAccessToken", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "GenerateAccessToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.GenerateAccessTokenRequest" - }, - { - "name": "workstation", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.types.GenerateAccessTokenResponse", - "shortName": "generate_access_token" - }, - "description": "Sample for GenerateAccessToken", - "file": "workstations_v1_generated_workstations_generate_access_token_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_GenerateAccessToken_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": "workstations_v1_generated_workstations_generate_access_token_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.generate_access_token", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.GenerateAccessToken", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "GenerateAccessToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.GenerateAccessTokenRequest" - }, - { - "name": "workstation", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1.types.GenerateAccessTokenResponse", - "shortName": "generate_access_token" - }, - "description": "Sample for GenerateAccessToken", - "file": "workstations_v1_generated_workstations_generate_access_token_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_GenerateAccessToken_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": "workstations_v1_generated_workstations_generate_access_token_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.get_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.GetWorkstationClusterRequest" - }, - { - "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.workstations_v1.types.WorkstationCluster", - "shortName": "get_workstation_cluster" - }, - "description": "Sample for GetWorkstationCluster", - "file": "workstations_v1_generated_workstations_get_workstation_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_GetWorkstationCluster_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": "workstations_v1_generated_workstations_get_workstation_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.get_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.GetWorkstationClusterRequest" - }, - { - "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.workstations_v1.types.WorkstationCluster", - "shortName": "get_workstation_cluster" - }, - "description": "Sample for GetWorkstationCluster", - "file": "workstations_v1_generated_workstations_get_workstation_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_GetWorkstationCluster_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": "workstations_v1_generated_workstations_get_workstation_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.get_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.GetWorkstationConfigRequest" - }, - { - "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.workstations_v1.types.WorkstationConfig", - "shortName": "get_workstation_config" - }, - "description": "Sample for GetWorkstationConfig", - "file": "workstations_v1_generated_workstations_get_workstation_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_GetWorkstationConfig_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": "workstations_v1_generated_workstations_get_workstation_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.get_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.GetWorkstationConfigRequest" - }, - { - "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.workstations_v1.types.WorkstationConfig", - "shortName": "get_workstation_config" - }, - "description": "Sample for GetWorkstationConfig", - "file": "workstations_v1_generated_workstations_get_workstation_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_GetWorkstationConfig_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": "workstations_v1_generated_workstations_get_workstation_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.get_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.GetWorkstationRequest" - }, - { - "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.workstations_v1.types.Workstation", - "shortName": "get_workstation" - }, - "description": "Sample for GetWorkstation", - "file": "workstations_v1_generated_workstations_get_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_GetWorkstation_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": "workstations_v1_generated_workstations_get_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.get_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.GetWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.GetWorkstationRequest" - }, - { - "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.workstations_v1.types.Workstation", - "shortName": "get_workstation" - }, - "description": "Sample for GetWorkstation", - "file": "workstations_v1_generated_workstations_get_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_GetWorkstation_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": "workstations_v1_generated_workstations_get_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_usable_workstation_configs", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListUsableWorkstationConfigs", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListUsableWorkstationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest" - }, - { - "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.workstations_v1.services.workstations.pagers.ListUsableWorkstationConfigsAsyncPager", - "shortName": "list_usable_workstation_configs" - }, - "description": "Sample for ListUsableWorkstationConfigs", - "file": "workstations_v1_generated_workstations_list_usable_workstation_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_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": "workstations_v1_generated_workstations_list_usable_workstation_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_usable_workstation_configs", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListUsableWorkstationConfigs", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListUsableWorkstationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListUsableWorkstationConfigsRequest" - }, - { - "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.workstations_v1.services.workstations.pagers.ListUsableWorkstationConfigsPager", - "shortName": "list_usable_workstation_configs" - }, - "description": "Sample for ListUsableWorkstationConfigs", - "file": "workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_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": "workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_usable_workstations", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListUsableWorkstations", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListUsableWorkstations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListUsableWorkstationsRequest" - }, - { - "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.workstations_v1.services.workstations.pagers.ListUsableWorkstationsAsyncPager", - "shortName": "list_usable_workstations" - }, - "description": "Sample for ListUsableWorkstations", - "file": "workstations_v1_generated_workstations_list_usable_workstations_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListUsableWorkstations_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": "workstations_v1_generated_workstations_list_usable_workstations_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_usable_workstations", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListUsableWorkstations", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListUsableWorkstations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListUsableWorkstationsRequest" - }, - { - "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.workstations_v1.services.workstations.pagers.ListUsableWorkstationsPager", - "shortName": "list_usable_workstations" - }, - "description": "Sample for ListUsableWorkstations", - "file": "workstations_v1_generated_workstations_list_usable_workstations_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListUsableWorkstations_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": "workstations_v1_generated_workstations_list_usable_workstations_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_workstation_clusters", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstationClusters", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstationClusters" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListWorkstationClustersRequest" - }, - { - "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.workstations_v1.services.workstations.pagers.ListWorkstationClustersAsyncPager", - "shortName": "list_workstation_clusters" - }, - "description": "Sample for ListWorkstationClusters", - "file": "workstations_v1_generated_workstations_list_workstation_clusters_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListWorkstationClusters_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": "workstations_v1_generated_workstations_list_workstation_clusters_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_workstation_clusters", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstationClusters", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstationClusters" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListWorkstationClustersRequest" - }, - { - "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.workstations_v1.services.workstations.pagers.ListWorkstationClustersPager", - "shortName": "list_workstation_clusters" - }, - "description": "Sample for ListWorkstationClusters", - "file": "workstations_v1_generated_workstations_list_workstation_clusters_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListWorkstationClusters_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": "workstations_v1_generated_workstations_list_workstation_clusters_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_workstation_configs", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstationConfigs", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListWorkstationConfigsRequest" - }, - { - "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.workstations_v1.services.workstations.pagers.ListWorkstationConfigsAsyncPager", - "shortName": "list_workstation_configs" - }, - "description": "Sample for ListWorkstationConfigs", - "file": "workstations_v1_generated_workstations_list_workstation_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListWorkstationConfigs_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": "workstations_v1_generated_workstations_list_workstation_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_workstation_configs", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstationConfigs", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListWorkstationConfigsRequest" - }, - { - "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.workstations_v1.services.workstations.pagers.ListWorkstationConfigsPager", - "shortName": "list_workstation_configs" - }, - "description": "Sample for ListWorkstationConfigs", - "file": "workstations_v1_generated_workstations_list_workstation_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListWorkstationConfigs_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": "workstations_v1_generated_workstations_list_workstation_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.list_workstations", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstations", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListWorkstationsRequest" - }, - { - "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.workstations_v1.services.workstations.pagers.ListWorkstationsAsyncPager", - "shortName": "list_workstations" - }, - "description": "Sample for ListWorkstations", - "file": "workstations_v1_generated_workstations_list_workstations_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListWorkstations_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": "workstations_v1_generated_workstations_list_workstations_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.list_workstations", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.ListWorkstations", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.ListWorkstationsRequest" - }, - { - "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.workstations_v1.services.workstations.pagers.ListWorkstationsPager", - "shortName": "list_workstations" - }, - "description": "Sample for ListWorkstations", - "file": "workstations_v1_generated_workstations_list_workstations_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_ListWorkstations_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": "workstations_v1_generated_workstations_list_workstations_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.start_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.StartWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "StartWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.StartWorkstationRequest" - }, - { - "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": "start_workstation" - }, - "description": "Sample for StartWorkstation", - "file": "workstations_v1_generated_workstations_start_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_StartWorkstation_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": "workstations_v1_generated_workstations_start_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.start_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.StartWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "StartWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.StartWorkstationRequest" - }, - { - "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": "start_workstation" - }, - "description": "Sample for StartWorkstation", - "file": "workstations_v1_generated_workstations_start_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_StartWorkstation_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": "workstations_v1_generated_workstations_start_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.stop_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.StopWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "StopWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.StopWorkstationRequest" - }, - { - "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": "stop_workstation" - }, - "description": "Sample for StopWorkstation", - "file": "workstations_v1_generated_workstations_stop_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_StopWorkstation_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": "workstations_v1_generated_workstations_stop_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.stop_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.StopWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "StopWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.StopWorkstationRequest" - }, - { - "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": "stop_workstation" - }, - "description": "Sample for StopWorkstation", - "file": "workstations_v1_generated_workstations_stop_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_StopWorkstation_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": "workstations_v1_generated_workstations_stop_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.update_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.UpdateWorkstationClusterRequest" - }, - { - "name": "workstation_cluster", - "type": "google.cloud.workstations_v1.types.WorkstationCluster" - }, - { - "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_workstation_cluster" - }, - "description": "Sample for UpdateWorkstationCluster", - "file": "workstations_v1_generated_workstations_update_workstation_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstationCluster_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": "workstations_v1_generated_workstations_update_workstation_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.update_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.UpdateWorkstationClusterRequest" - }, - { - "name": "workstation_cluster", - "type": "google.cloud.workstations_v1.types.WorkstationCluster" - }, - { - "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_workstation_cluster" - }, - "description": "Sample for UpdateWorkstationCluster", - "file": "workstations_v1_generated_workstations_update_workstation_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstationCluster_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": "workstations_v1_generated_workstations_update_workstation_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.update_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.UpdateWorkstationConfigRequest" - }, - { - "name": "workstation_config", - "type": "google.cloud.workstations_v1.types.WorkstationConfig" - }, - { - "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_workstation_config" - }, - "description": "Sample for UpdateWorkstationConfig", - "file": "workstations_v1_generated_workstations_update_workstation_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstationConfig_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": "workstations_v1_generated_workstations_update_workstation_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.update_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.UpdateWorkstationConfigRequest" - }, - { - "name": "workstation_config", - "type": "google.cloud.workstations_v1.types.WorkstationConfig" - }, - { - "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_workstation_config" - }, - "description": "Sample for UpdateWorkstationConfig", - "file": "workstations_v1_generated_workstations_update_workstation_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstationConfig_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": "workstations_v1_generated_workstations_update_workstation_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsAsyncClient.update_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.UpdateWorkstationRequest" - }, - { - "name": "workstation", - "type": "google.cloud.workstations_v1.types.Workstation" - }, - { - "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_workstation" - }, - "description": "Sample for UpdateWorkstation", - "file": "workstations_v1_generated_workstations_update_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstation_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": "workstations_v1_generated_workstations_update_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1.WorkstationsClient.update_workstation", - "method": { - "fullName": "google.cloud.workstations.v1.Workstations.UpdateWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1.types.UpdateWorkstationRequest" - }, - { - "name": "workstation", - "type": "google.cloud.workstations_v1.types.Workstation" - }, - { - "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_workstation" - }, - "description": "Sample for UpdateWorkstation", - "file": "workstations_v1_generated_workstations_update_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1_generated_Workstations_UpdateWorkstation_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": "workstations_v1_generated_workstations_update_workstation_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_async.py deleted file mode 100644 index 89a8344d0ea6..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_CreateWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_create_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationRequest( - parent="parent_value", - workstation_id="workstation_id_value", - ) - - # Make the request - operation = client.create_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_CreateWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_async.py deleted file mode 100644 index d27a68364a39..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_CreateWorkstationCluster_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_create_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationClusterRequest( - parent="parent_value", - workstation_cluster_id="workstation_cluster_id_value", - ) - - # Make the request - operation = client.create_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_CreateWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_sync.py deleted file mode 100644 index cac2a6b31678..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_cluster_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_CreateWorkstationCluster_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_create_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationClusterRequest( - parent="parent_value", - workstation_cluster_id="workstation_cluster_id_value", - ) - - # Make the request - operation = client.create_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_CreateWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_async.py deleted file mode 100644 index d84606878316..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_CreateWorkstationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_create_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationConfigRequest( - parent="parent_value", - workstation_config_id="workstation_config_id_value", - ) - - # Make the request - operation = client.create_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_CreateWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_sync.py deleted file mode 100644 index 2793998a735b..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_config_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_CreateWorkstationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_create_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationConfigRequest( - parent="parent_value", - workstation_config_id="workstation_config_id_value", - ) - - # Make the request - operation = client.create_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_CreateWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_sync.py deleted file mode 100644 index 0f5fc372cb1a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_create_workstation_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_CreateWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_create_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.CreateWorkstationRequest( - parent="parent_value", - workstation_id="workstation_id_value", - ) - - # Make the request - operation = client.create_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_CreateWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_async.py deleted file mode 100644 index 7cef6fd6f42f..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_DeleteWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_delete_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_DeleteWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_async.py deleted file mode 100644 index 6f5c9cf4e567..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_DeleteWorkstationCluster_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_delete_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_DeleteWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_sync.py deleted file mode 100644 index bdc26bc6599e..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_cluster_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_DeleteWorkstationCluster_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_delete_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_DeleteWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_async.py deleted file mode 100644 index 1954a3d63121..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_DeleteWorkstationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_delete_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_DeleteWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_sync.py deleted file mode 100644 index 0883ac378b5a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_config_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_DeleteWorkstationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_delete_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_DeleteWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_sync.py deleted file mode 100644 index 96be92bcf338..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_delete_workstation_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_DeleteWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_delete_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.DeleteWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_DeleteWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_async.py deleted file mode 100644 index 7c38f6f86ce9..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateAccessToken -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_GenerateAccessToken_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_generate_access_token(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.GenerateAccessTokenRequest( - workstation="workstation_value", - ) - - # Make the request - response = await client.generate_access_token(request=request) - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_GenerateAccessToken_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_sync.py deleted file mode 100644 index 872470075a79..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_generate_access_token_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateAccessToken -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_GenerateAccessToken_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_generate_access_token(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.GenerateAccessTokenRequest( - workstation="workstation_value", - ) - - # Make the request - response = client.generate_access_token(request=request) - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_GenerateAccessToken_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_async.py deleted file mode 100644 index 6a893b9d9dc7..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_GetWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_get_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation(request=request) - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_GetWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_async.py deleted file mode 100644 index b989470d3f42..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_GetWorkstationCluster_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_get_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation_cluster(request=request) - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_GetWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_sync.py deleted file mode 100644 index ae396a9e7538..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_cluster_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_GetWorkstationCluster_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_get_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation_cluster(request=request) - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_GetWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_async.py deleted file mode 100644 index 585e7e653b43..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_GetWorkstationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_get_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation_config(request=request) - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_GetWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_sync.py deleted file mode 100644 index 31226bc5c8b8..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_config_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_GetWorkstationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_get_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation_config(request=request) - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_GetWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_sync.py deleted file mode 100644 index e5fc47e62da5..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_get_workstation_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_GetWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_get_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.GetWorkstationRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation(request=request) - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_GetWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_async.py deleted file mode 100644 index d4a502988bd7..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListUsableWorkstationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_list_usable_workstation_configs(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListUsableWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstation_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py deleted file mode 100644 index dbc338eb4b89..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstation_configs_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListUsableWorkstationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_list_usable_workstation_configs(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListUsableWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstation_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListUsableWorkstationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_async.py deleted file mode 100644 index 89020a9b2551..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListUsableWorkstations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListUsableWorkstations_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_list_usable_workstations(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListUsableWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstations(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListUsableWorkstations_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_sync.py deleted file mode 100644 index 33e592f08dc2..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_usable_workstations_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListUsableWorkstations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListUsableWorkstations_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_list_usable_workstations(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListUsableWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstations(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListUsableWorkstations_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_async.py deleted file mode 100644 index 5b819c9660a2..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListWorkstationClusters -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListWorkstationClusters_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_list_workstation_clusters(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_clusters(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListWorkstationClusters_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_sync.py deleted file mode 100644 index b5ae979380d8..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_clusters_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListWorkstationClusters -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListWorkstationClusters_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_list_workstation_clusters(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_clusters(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListWorkstationClusters_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_async.py deleted file mode 100644 index 9254e3a40e17..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListWorkstationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListWorkstationConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_list_workstation_configs(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListWorkstationConfigs_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_sync.py deleted file mode 100644 index 855946d5d01d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstation_configs_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListWorkstationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListWorkstationConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_list_workstation_configs(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListWorkstationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_async.py deleted file mode 100644 index b958d7af6e06..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListWorkstations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListWorkstations_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_list_workstations(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstations(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListWorkstations_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_sync.py deleted file mode 100644 index 5fb7c29d70e6..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_list_workstations_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListWorkstations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_ListWorkstations_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_list_workstations(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.ListWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstations(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1_generated_Workstations_ListWorkstations_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_async.py deleted file mode 100644 index f58aa3ede984..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StartWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_StartWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_start_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.StartWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.start_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_StartWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_sync.py deleted file mode 100644 index 3cfeee47342b..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_start_workstation_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StartWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_StartWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_start_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.StartWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.start_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_StartWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_async.py deleted file mode 100644 index 080617e3ee48..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StopWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_StopWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_stop_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.StopWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.stop_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_StopWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_sync.py deleted file mode 100644 index bd811dc972f5..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_stop_workstation_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StopWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_StopWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_stop_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.StopWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.stop_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_StopWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_async.py deleted file mode 100644 index 12a7cc9fa3a3..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_UpdateWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_update_workstation(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationRequest( - ) - - # Make the request - operation = client.update_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_UpdateWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_async.py deleted file mode 100644 index b635ef7d3369..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_UpdateWorkstationCluster_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_update_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationClusterRequest( - ) - - # Make the request - operation = client.update_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_UpdateWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_sync.py deleted file mode 100644 index 7d0418825c0a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_cluster_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_UpdateWorkstationCluster_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_update_workstation_cluster(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationClusterRequest( - ) - - # Make the request - operation = client.update_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_UpdateWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_async.py deleted file mode 100644 index d2f99b937d22..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_UpdateWorkstationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -async def sample_update_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationConfigRequest( - ) - - # Make the request - operation = client.update_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_UpdateWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_sync.py deleted file mode 100644 index 93fde4da6273..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_config_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_UpdateWorkstationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_update_workstation_config(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationConfigRequest( - ) - - # Make the request - operation = client.update_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_UpdateWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_sync.py deleted file mode 100644 index 23796c1a85db..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/samples/generated_samples/workstations_v1_generated_workstations_update_workstation_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1_generated_Workstations_UpdateWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1 - - -def sample_update_workstation(): - # Create a client - client = workstations_v1.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1.UpdateWorkstationRequest( - ) - - # Make the request - operation = client.update_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1_generated_Workstations_UpdateWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1/scripts/fixup_workstations_v1_keywords.py b/owl-bot-staging/google-cloud-workstations/v1/scripts/fixup_workstations_v1_keywords.py deleted file mode 100644 index 4f7ba7cb1e17..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/scripts/fixup_workstations_v1_keywords.py +++ /dev/null @@ -1,195 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 workstationsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_workstation': ('parent', 'workstation_id', 'workstation', 'validate_only', ), - 'create_workstation_cluster': ('parent', 'workstation_cluster_id', 'workstation_cluster', 'validate_only', ), - 'create_workstation_config': ('parent', 'workstation_config_id', 'workstation_config', 'validate_only', ), - 'delete_workstation': ('name', 'validate_only', 'etag', ), - 'delete_workstation_cluster': ('name', 'validate_only', 'etag', 'force', ), - 'delete_workstation_config': ('name', 'validate_only', 'etag', 'force', ), - 'generate_access_token': ('workstation', 'expire_time', 'ttl', ), - 'get_workstation': ('name', ), - 'get_workstation_cluster': ('name', ), - 'get_workstation_config': ('name', ), - 'list_usable_workstation_configs': ('parent', 'page_size', 'page_token', ), - 'list_usable_workstations': ('parent', 'page_size', 'page_token', ), - 'list_workstation_clusters': ('parent', 'page_size', 'page_token', ), - 'list_workstation_configs': ('parent', 'page_size', 'page_token', ), - 'list_workstations': ('parent', 'page_size', 'page_token', ), - 'start_workstation': ('name', 'validate_only', 'etag', ), - 'stop_workstation': ('name', 'validate_only', 'etag', ), - 'update_workstation': ('workstation', 'update_mask', 'validate_only', 'allow_missing', ), - 'update_workstation_cluster': ('workstation_cluster', 'update_mask', 'validate_only', 'allow_missing', ), - 'update_workstation_config': ('workstation_config', 'update_mask', 'validate_only', 'allow_missing', ), - } - - 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=workstationsCallTransformer(), -): - """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 workstations client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-workstations/v1/setup.py b/owl-bot-staging/google-cloud-workstations/v1/setup.py deleted file mode 100644 index 1483952d60ff..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/setup.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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-workstations' - - -description = "Google Cloud Workstations API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/workstations/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-workstations" - -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/google-cloud-workstations/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.7.txt deleted file mode 100644 index 2beecf99e0be..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 -grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1/tests/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/tests/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-workstations/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/__init__.py b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/test_workstations.py b/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/test_workstations.py deleted file mode 100644 index cbb58219b309..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1/tests/unit/gapic/workstations_v1/test_workstations.py +++ /dev/null @@ -1,13498 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.location import locations_pb2 -from google.cloud.workstations_v1.services.workstations import WorkstationsAsyncClient -from google.cloud.workstations_v1.services.workstations import WorkstationsClient -from google.cloud.workstations_v1.services.workstations import pagers -from google.cloud.workstations_v1.services.workstations import transports -from google.cloud.workstations_v1.types import workstations -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 any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_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 WorkstationsClient._get_default_mtls_endpoint(None) is None - assert WorkstationsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert WorkstationsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert WorkstationsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert WorkstationsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert WorkstationsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (WorkstationsClient, "grpc"), - (WorkstationsAsyncClient, "grpc_asyncio"), - (WorkstationsClient, "rest"), -]) -def test_workstations_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 == ( - 'workstations.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://workstations.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.WorkstationsGrpcTransport, "grpc"), - (transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.WorkstationsRestTransport, "rest"), -]) -def test_workstations_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", [ - (WorkstationsClient, "grpc"), - (WorkstationsAsyncClient, "grpc_asyncio"), - (WorkstationsClient, "rest"), -]) -def test_workstations_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 == ( - 'workstations.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://workstations.googleapis.com' - ) - - -def test_workstations_client_get_transport_class(): - transport = WorkstationsClient.get_transport_class() - available_transports = [ - transports.WorkstationsGrpcTransport, - transports.WorkstationsRestTransport, - ] - assert transport in available_transports - - transport = WorkstationsClient.get_transport_class("grpc") - assert transport == transports.WorkstationsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), -]) -@mock.patch.object(WorkstationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsClient)) -@mock.patch.object(WorkstationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsAsyncClient)) -def test_workstations_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(WorkstationsClient, '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(WorkstationsClient, '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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", "true"), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", "false"), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest", "true"), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest", "false"), -]) -@mock.patch.object(WorkstationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsClient)) -@mock.patch.object(WorkstationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_workstations_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", [ - WorkstationsClient, WorkstationsAsyncClient -]) -@mock.patch.object(WorkstationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsClient)) -@mock.patch.object(WorkstationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsAsyncClient)) -def test_workstations_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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), -]) -def test_workstations_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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", grpc_helpers), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest", None), -]) -def test_workstations_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_workstations_client_client_options_from_dict(): - with mock.patch('google.cloud.workstations_v1.services.workstations.transports.WorkstationsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = WorkstationsClient( - 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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", grpc_helpers), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_workstations_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( - "workstations.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="workstations.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationClusterRequest, - dict, -]) -def test_get_workstation_cluster(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationCluster( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - network='network_value', - subnetwork='subnetwork_value', - control_plane_ip='control_plane_ip_value', - degraded=True, - ) - response = client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationClusterRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationCluster) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.network == 'network_value' - assert response.subnetwork == 'subnetwork_value' - assert response.control_plane_ip == 'control_plane_ip_value' - assert response.degraded is True - - -def test_get_workstation_cluster_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_cluster), - '__call__') as call: - client.get_workstation_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationClusterRequest() - -@pytest.mark.asyncio -async def test_get_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationClusterRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - network='network_value', - subnetwork='subnetwork_value', - control_plane_ip='control_plane_ip_value', - degraded=True, - )) - response = await client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationClusterRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationCluster) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.network == 'network_value' - assert response.subnetwork == 'subnetwork_value' - assert response.control_plane_ip == 'control_plane_ip_value' - assert response.degraded is True - - -@pytest.mark.asyncio -async def test_get_workstation_cluster_async_from_dict(): - await test_get_workstation_cluster_async(request_type=dict) - - -def test_get_workstation_cluster_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - call.return_value = workstations.WorkstationCluster() - client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster()) - await client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationCluster() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_workstation_cluster( - 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_workstation_cluster_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_cluster( - workstations.GetWorkstationClusterRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_workstation_cluster_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationCluster() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_workstation_cluster( - 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_workstation_cluster_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_cluster( - workstations.GetWorkstationClusterRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationClustersRequest, - dict, -]) -def test_list_workstation_clusters(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationClustersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationClustersRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationClustersPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workstation_clusters_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_clusters), - '__call__') as call: - client.list_workstation_clusters() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationClustersRequest() - -@pytest.mark.asyncio -async def test_list_workstation_clusters_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationClustersRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationClustersRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationClustersAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_workstation_clusters_async_from_dict(): - await test_list_workstation_clusters_async(request_type=dict) - - -def test_list_workstation_clusters_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationClustersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - call.return_value = workstations.ListWorkstationClustersResponse() - client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_workstation_clusters_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationClustersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse()) - await client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_workstation_clusters_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationClustersResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_workstation_clusters( - 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_workstation_clusters_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_clusters( - workstations.ListWorkstationClustersRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_workstation_clusters_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationClustersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_workstation_clusters( - 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_workstation_clusters_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_clusters( - workstations.ListWorkstationClustersRequest(), - parent='parent_value', - ) - - -def test_list_workstation_clusters_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstation_clusters), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_workstation_clusters(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.WorkstationCluster) - for i in results) -def test_list_workstation_clusters_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstation_clusters), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - RuntimeError, - ) - pages = list(client.list_workstation_clusters(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_workstation_clusters_async_pager(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_workstation_clusters(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, workstations.WorkstationCluster) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_workstation_clusters_async_pages(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_workstation_clusters(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - workstations.CreateWorkstationClusterRequest, - dict, -]) -def test_create_workstation_cluster(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationClusterRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_workstation_cluster_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_cluster), - '__call__') as call: - client.create_workstation_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationClusterRequest() - -@pytest.mark.asyncio -async def test_create_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationClusterRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__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_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationClusterRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_workstation_cluster_async_from_dict(): - await test_create_workstation_cluster_async(request_type=dict) - - -def test_create_workstation_cluster_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationClusterRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_workstation_cluster_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationClusterRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_workstation_cluster_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__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_workstation_cluster( - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].workstation_cluster - mock_val = workstations.WorkstationCluster(name='name_value') - assert arg == mock_val - arg = args[0].workstation_cluster_id - mock_val = 'workstation_cluster_id_value' - assert arg == mock_val - - -def test_create_workstation_cluster_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_cluster( - workstations.CreateWorkstationClusterRequest(), - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_value', - ) - -@pytest.mark.asyncio -async def test_create_workstation_cluster_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__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_workstation_cluster( - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].workstation_cluster - mock_val = workstations.WorkstationCluster(name='name_value') - assert arg == mock_val - arg = args[0].workstation_cluster_id - mock_val = 'workstation_cluster_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_workstation_cluster_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_cluster( - workstations.CreateWorkstationClusterRequest(), - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationClusterRequest, - dict, -]) -def test_update_workstation_cluster(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationClusterRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_workstation_cluster_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_cluster), - '__call__') as call: - client.update_workstation_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationClusterRequest() - -@pytest.mark.asyncio -async def test_update_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationClusterRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__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_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationClusterRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_workstation_cluster_async_from_dict(): - await test_update_workstation_cluster_async(request_type=dict) - - -def test_update_workstation_cluster_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationClusterRequest() - - request.workstation_cluster.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation_cluster.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_workstation_cluster_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationClusterRequest() - - request.workstation_cluster.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation_cluster.name=name_value', - ) in kw['metadata'] - - -def test_update_workstation_cluster_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__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_workstation_cluster( - workstation_cluster=workstations.WorkstationCluster(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].workstation_cluster - mock_val = workstations.WorkstationCluster(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_workstation_cluster_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_cluster( - workstations.UpdateWorkstationClusterRequest(), - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_workstation_cluster_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__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_workstation_cluster( - workstation_cluster=workstations.WorkstationCluster(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].workstation_cluster - mock_val = workstations.WorkstationCluster(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_workstation_cluster_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_cluster( - workstations.UpdateWorkstationClusterRequest(), - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationClusterRequest, - dict, -]) -def test_delete_workstation_cluster(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationClusterRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_workstation_cluster_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_cluster), - '__call__') as call: - client.delete_workstation_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationClusterRequest() - -@pytest.mark.asyncio -async def test_delete_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationClusterRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__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_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationClusterRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_workstation_cluster_async_from_dict(): - await test_delete_workstation_cluster_async(request_type=dict) - - -def test_delete_workstation_cluster_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__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_workstation_cluster( - 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_workstation_cluster_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_cluster( - workstations.DeleteWorkstationClusterRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_workstation_cluster_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__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_workstation_cluster( - 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_workstation_cluster_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_cluster( - workstations.DeleteWorkstationClusterRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationConfigRequest, - dict, -]) -def test_get_workstation_config(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationConfig( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - degraded=True, - ) - response = client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.degraded is True - - -def test_get_workstation_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_config), - '__call__') as call: - client.get_workstation_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationConfigRequest() - -@pytest.mark.asyncio -async def test_get_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationConfigRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - degraded=True, - )) - response = await client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.degraded is True - - -@pytest.mark.asyncio -async def test_get_workstation_config_async_from_dict(): - await test_get_workstation_config_async(request_type=dict) - - -def test_get_workstation_config_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - call.return_value = workstations.WorkstationConfig() - client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_workstation_config_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig()) - await client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_workstation_config_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_workstation_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_workstation_config_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_config( - workstations.GetWorkstationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_workstation_config_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_workstation_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_workstation_config_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_config( - workstations.GetWorkstationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationConfigsRequest, - dict, -]) -def test_list_workstation_configs(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workstation_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_configs), - '__call__') as call: - client.list_workstation_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationConfigsRequest() - -@pytest.mark.asyncio -async def test_list_workstation_configs_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationConfigsRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_workstation_configs_async_from_dict(): - await test_list_workstation_configs_async(request_type=dict) - - -def test_list_workstation_configs_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - call.return_value = workstations.ListWorkstationConfigsResponse() - client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_workstation_configs_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse()) - await client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_workstation_configs_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_workstation_configs( - 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_workstation_configs_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_configs( - workstations.ListWorkstationConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_workstation_configs_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_workstation_configs( - 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_workstation_configs_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_configs( - workstations.ListWorkstationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_workstation_configs_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstation_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_workstation_configs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.WorkstationConfig) - for i in results) -def test_list_workstation_configs_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstation_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_workstation_configs(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_workstation_configs_async_pager(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_workstation_configs(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, workstations.WorkstationConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_workstation_configs_async_pages(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_workstation_configs(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - workstations.ListUsableWorkstationConfigsRequest, - dict, -]) -def test_list_usable_workstation_configs(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_usable_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListUsableWorkstationConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_usable_workstation_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_usable_workstation_configs), - '__call__') as call: - client.list_usable_workstation_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListUsableWorkstationConfigsRequest() - -@pytest.mark.asyncio -async def test_list_usable_workstation_configs_async(transport: str = 'grpc_asyncio', request_type=workstations.ListUsableWorkstationConfigsRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_usable_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListUsableWorkstationConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_usable_workstation_configs_async_from_dict(): - await test_list_usable_workstation_configs_async(request_type=dict) - - -def test_list_usable_workstation_configs_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListUsableWorkstationConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - call.return_value = workstations.ListUsableWorkstationConfigsResponse() - client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_usable_workstation_configs_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListUsableWorkstationConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse()) - await client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_usable_workstation_configs_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_usable_workstation_configs( - 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_usable_workstation_configs_flattened_error(): - client = WorkstationsClient( - credentials=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_usable_workstation_configs( - workstations.ListUsableWorkstationConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_usable_workstation_configs_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_usable_workstation_configs( - 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_usable_workstation_configs_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_usable_workstation_configs( - workstations.ListUsableWorkstationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_usable_workstation_configs_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_usable_workstation_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_usable_workstation_configs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.WorkstationConfig) - for i in results) -def test_list_usable_workstation_configs_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_usable_workstation_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_usable_workstation_configs(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_usable_workstation_configs_async_pager(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_usable_workstation_configs(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, workstations.WorkstationConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_usable_workstation_configs_async_pages(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_usable_workstation_configs(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - workstations.CreateWorkstationConfigRequest, - dict, -]) -def test_create_workstation_config(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_workstation_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_config), - '__call__') as call: - client.create_workstation_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationConfigRequest() - -@pytest.mark.asyncio -async def test_create_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationConfigRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__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_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_workstation_config_async_from_dict(): - await test_create_workstation_config_async(request_type=dict) - - -def test_create_workstation_config_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_workstation_config_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_workstation_config_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__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_workstation_config( - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].workstation_config - mock_val = workstations.WorkstationConfig(name='name_value') - assert arg == mock_val - arg = args[0].workstation_config_id - mock_val = 'workstation_config_id_value' - assert arg == mock_val - - -def test_create_workstation_config_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_config( - workstations.CreateWorkstationConfigRequest(), - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_value', - ) - -@pytest.mark.asyncio -async def test_create_workstation_config_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__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_workstation_config( - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].workstation_config - mock_val = workstations.WorkstationConfig(name='name_value') - assert arg == mock_val - arg = args[0].workstation_config_id - mock_val = 'workstation_config_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_workstation_config_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_config( - workstations.CreateWorkstationConfigRequest(), - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationConfigRequest, - dict, -]) -def test_update_workstation_config(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_workstation_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_config), - '__call__') as call: - client.update_workstation_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationConfigRequest() - -@pytest.mark.asyncio -async def test_update_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationConfigRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__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_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_workstation_config_async_from_dict(): - await test_update_workstation_config_async(request_type=dict) - - -def test_update_workstation_config_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationConfigRequest() - - request.workstation_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_workstation_config_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationConfigRequest() - - request.workstation_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation_config.name=name_value', - ) in kw['metadata'] - - -def test_update_workstation_config_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__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_workstation_config( - workstation_config=workstations.WorkstationConfig(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].workstation_config - mock_val = workstations.WorkstationConfig(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_workstation_config_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_config( - workstations.UpdateWorkstationConfigRequest(), - workstation_config=workstations.WorkstationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_workstation_config_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__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_workstation_config( - workstation_config=workstations.WorkstationConfig(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].workstation_config - mock_val = workstations.WorkstationConfig(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_workstation_config_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_config( - workstations.UpdateWorkstationConfigRequest(), - workstation_config=workstations.WorkstationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationConfigRequest, - dict, -]) -def test_delete_workstation_config(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_workstation_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_config), - '__call__') as call: - client.delete_workstation_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationConfigRequest() - -@pytest.mark.asyncio -async def test_delete_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationConfigRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__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_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_workstation_config_async_from_dict(): - await test_delete_workstation_config_async(request_type=dict) - - -def test_delete_workstation_config_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_workstation_config_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_workstation_config_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__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_workstation_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_workstation_config_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_config( - workstations.DeleteWorkstationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_workstation_config_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__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_workstation_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_workstation_config_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_config( - workstations.DeleteWorkstationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationRequest, - dict, -]) -def test_get_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.Workstation( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - state=workstations.Workstation.State.STATE_STARTING, - host='host_value', - ) - response = client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.Workstation) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.state == workstations.Workstation.State.STATE_STARTING - assert response.host == 'host_value' - - -def test_get_workstation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation), - '__call__') as call: - client.get_workstation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationRequest() - -@pytest.mark.asyncio -async def test_get_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - state=workstations.Workstation.State.STATE_STARTING, - host='host_value', - )) - response = await client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.Workstation) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.state == workstations.Workstation.State.STATE_STARTING - assert response.host == 'host_value' - - -@pytest.mark.asyncio -async def test_get_workstation_async_from_dict(): - await test_get_workstation_async(request_type=dict) - - -def test_get_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - call.return_value = workstations.Workstation() - client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation()) - await client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.Workstation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_workstation( - 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_workstation_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation( - workstations.GetWorkstationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.Workstation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_workstation( - 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_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation( - workstations.GetWorkstationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationsRequest, - dict, -]) -def test_list_workstations(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workstations_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstations), - '__call__') as call: - client.list_workstations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationsRequest() - -@pytest.mark.asyncio -async def test_list_workstations_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationsRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_workstations_async_from_dict(): - await test_list_workstations_async(request_type=dict) - - -def test_list_workstations_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - call.return_value = workstations.ListWorkstationsResponse() - client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_workstations_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse()) - await client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_workstations_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_workstations( - 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_workstations_flattened_error(): - client = WorkstationsClient( - credentials=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_workstations( - workstations.ListWorkstationsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_workstations_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_workstations( - 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_workstations_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstations( - workstations.ListWorkstationsRequest(), - parent='parent_value', - ) - - -def test_list_workstations_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_workstations(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.Workstation) - for i in results) -def test_list_workstations_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - pages = list(client.list_workstations(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_workstations_async_pager(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_workstations(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, workstations.Workstation) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_workstations_async_pages(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_workstations(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - workstations.ListUsableWorkstationsRequest, - dict, -]) -def test_list_usable_workstations(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_usable_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListUsableWorkstationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_usable_workstations_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_usable_workstations), - '__call__') as call: - client.list_usable_workstations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListUsableWorkstationsRequest() - -@pytest.mark.asyncio -async def test_list_usable_workstations_async(transport: str = 'grpc_asyncio', request_type=workstations.ListUsableWorkstationsRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_usable_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListUsableWorkstationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_usable_workstations_async_from_dict(): - await test_list_usable_workstations_async(request_type=dict) - - -def test_list_usable_workstations_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListUsableWorkstationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - call.return_value = workstations.ListUsableWorkstationsResponse() - client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_usable_workstations_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListUsableWorkstationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse()) - await client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_usable_workstations_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_usable_workstations( - 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_usable_workstations_flattened_error(): - client = WorkstationsClient( - credentials=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_usable_workstations( - workstations.ListUsableWorkstationsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_usable_workstations_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_usable_workstations( - 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_usable_workstations_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_usable_workstations( - workstations.ListUsableWorkstationsRequest(), - parent='parent_value', - ) - - -def test_list_usable_workstations_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_usable_workstations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_usable_workstations(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.Workstation) - for i in results) -def test_list_usable_workstations_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_usable_workstations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - pages = list(client.list_usable_workstations(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_usable_workstations_async_pager(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_usable_workstations(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, workstations.Workstation) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_usable_workstations_async_pages(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_usable_workstations(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - workstations.CreateWorkstationRequest, - dict, -]) -def test_create_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_workstation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation), - '__call__') as call: - client.create_workstation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationRequest() - -@pytest.mark.asyncio -async def test_create_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__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_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_workstation_async_from_dict(): - await test_create_workstation_async(request_type=dict) - - -def test_create_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__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_workstation( - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].workstation - mock_val = workstations.Workstation(name='name_value') - assert arg == mock_val - arg = args[0].workstation_id - mock_val = 'workstation_id_value' - assert arg == mock_val - - -def test_create_workstation_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation( - workstations.CreateWorkstationRequest(), - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_value', - ) - -@pytest.mark.asyncio -async def test_create_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__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_workstation( - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].workstation - mock_val = workstations.Workstation(name='name_value') - assert arg == mock_val - arg = args[0].workstation_id - mock_val = 'workstation_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation( - workstations.CreateWorkstationRequest(), - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationRequest, - dict, -]) -def test_update_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_workstation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation), - '__call__') as call: - client.update_workstation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationRequest() - -@pytest.mark.asyncio -async def test_update_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__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_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_workstation_async_from_dict(): - await test_update_workstation_async(request_type=dict) - - -def test_update_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationRequest() - - request.workstation.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationRequest() - - request.workstation.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation.name=name_value', - ) in kw['metadata'] - - -def test_update_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__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_workstation( - workstation=workstations.Workstation(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].workstation - mock_val = workstations.Workstation(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_workstation_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation( - workstations.UpdateWorkstationRequest(), - workstation=workstations.Workstation(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__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_workstation( - workstation=workstations.Workstation(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].workstation - mock_val = workstations.Workstation(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_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation( - workstations.UpdateWorkstationRequest(), - workstation=workstations.Workstation(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationRequest, - dict, -]) -def test_delete_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_workstation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation), - '__call__') as call: - client.delete_workstation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationRequest() - -@pytest.mark.asyncio -async def test_delete_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__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_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_workstation_async_from_dict(): - await test_delete_workstation_async(request_type=dict) - - -def test_delete_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__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_workstation( - 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_workstation_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation( - workstations.DeleteWorkstationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__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_workstation( - 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_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation( - workstations.DeleteWorkstationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.StartWorkstationRequest, - dict, -]) -def test_start_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.start_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.StartWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_start_workstation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - client.start_workstation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.StartWorkstationRequest() - -@pytest.mark.asyncio -async def test_start_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.StartWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__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.start_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.StartWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_start_workstation_async_from_dict(): - await test_start_workstation_async(request_type=dict) - - -def test_start_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.StartWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.start_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_start_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.StartWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.start_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_start_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__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.start_workstation( - 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_start_workstation_flattened_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.start_workstation( - workstations.StartWorkstationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_start_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__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.start_workstation( - 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_start_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - 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.start_workstation( - workstations.StartWorkstationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.StopWorkstationRequest, - dict, -]) -def test_stop_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.stop_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.StopWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_stop_workstation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - client.stop_workstation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.StopWorkstationRequest() - -@pytest.mark.asyncio -async def test_stop_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.StopWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__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.stop_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.StopWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_stop_workstation_async_from_dict(): - await test_stop_workstation_async(request_type=dict) - - -def test_stop_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.StopWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.stop_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_stop_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.StopWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.stop_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_stop_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__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.stop_workstation( - 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_stop_workstation_flattened_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.stop_workstation( - workstations.StopWorkstationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_stop_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__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.stop_workstation( - 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_stop_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - 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.stop_workstation( - workstations.StopWorkstationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GenerateAccessTokenRequest, - dict, -]) -def test_generate_access_token(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.GenerateAccessTokenResponse( - access_token='access_token_value', - ) - response = client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GenerateAccessTokenRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.GenerateAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -def test_generate_access_token_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - client.generate_access_token() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GenerateAccessTokenRequest() - -@pytest.mark.asyncio -async def test_generate_access_token_async(transport: str = 'grpc_asyncio', request_type=workstations.GenerateAccessTokenRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse( - access_token='access_token_value', - )) - response = await client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GenerateAccessTokenRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.GenerateAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -@pytest.mark.asyncio -async def test_generate_access_token_async_from_dict(): - await test_generate_access_token_async(request_type=dict) - - -def test_generate_access_token_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GenerateAccessTokenRequest() - - request.workstation = 'workstation_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - call.return_value = workstations.GenerateAccessTokenResponse() - client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation=workstation_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_generate_access_token_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GenerateAccessTokenRequest() - - request.workstation = 'workstation_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse()) - await client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation=workstation_value', - ) in kw['metadata'] - - -def test_generate_access_token_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.GenerateAccessTokenResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.generate_access_token( - workstation='workstation_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].workstation - mock_val = 'workstation_value' - assert arg == mock_val - - -def test_generate_access_token_flattened_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.generate_access_token( - workstations.GenerateAccessTokenRequest(), - workstation='workstation_value', - ) - -@pytest.mark.asyncio -async def test_generate_access_token_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.GenerateAccessTokenResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.generate_access_token( - workstation='workstation_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].workstation - mock_val = 'workstation_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_generate_access_token_flattened_error_async(): - client = WorkstationsAsyncClient( - 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.generate_access_token( - workstations.GenerateAccessTokenRequest(), - workstation='workstation_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationClusterRequest, - dict, -]) -def test_get_workstation_cluster_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationCluster( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - network='network_value', - subnetwork='subnetwork_value', - control_plane_ip='control_plane_ip_value', - degraded=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.WorkstationCluster.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_workstation_cluster(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationCluster) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.network == 'network_value' - assert response.subnetwork == 'subnetwork_value' - assert response.control_plane_ip == 'control_plane_ip_value' - assert response.degraded is True - - -def test_get_workstation_cluster_rest_required_fields(request_type=workstations.GetWorkstationClusterRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_cluster._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_workstation_cluster._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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationCluster() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # 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 = workstations.WorkstationCluster.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_workstation_cluster(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_workstation_cluster_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_workstation_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_workstation_cluster_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation_cluster") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.GetWorkstationClusterRequest.pb(workstations.GetWorkstationClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = workstations.WorkstationCluster.to_json(workstations.WorkstationCluster()) - - request = workstations.GetWorkstationClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.WorkstationCluster() - - client.get_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_workstation_cluster_rest_bad_request(transport: str = 'rest', request_type=workstations.GetWorkstationClusterRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_workstation_cluster(request) - - -def test_get_workstation_cluster_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationCluster() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.WorkstationCluster.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_workstation_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) - - -def test_get_workstation_cluster_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_cluster( - workstations.GetWorkstationClusterRequest(), - name='name_value', - ) - - -def test_get_workstation_cluster_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationClustersRequest, - dict, -]) -def test_list_workstation_clusters_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationClustersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListWorkstationClustersResponse.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_workstation_clusters(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationClustersPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workstation_clusters_rest_required_fields(request_type=workstations.ListWorkstationClustersRequest): - transport_class = transports.WorkstationsRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstation_clusters._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstation_clusters._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationClustersResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # 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 = workstations.ListWorkstationClustersResponse.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_workstation_clusters(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_workstation_clusters_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_workstation_clusters._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_workstation_clusters_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstation_clusters") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstation_clusters") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListWorkstationClustersRequest.pb(workstations.ListWorkstationClustersRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = workstations.ListWorkstationClustersResponse.to_json(workstations.ListWorkstationClustersResponse()) - - request = workstations.ListWorkstationClustersRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListWorkstationClustersResponse() - - client.list_workstation_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_workstation_clusters_rest_bad_request(transport: str = 'rest', request_type=workstations.ListWorkstationClustersRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_workstation_clusters(request) - - -def test_list_workstation_clusters_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationClustersResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListWorkstationClustersResponse.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_workstation_clusters(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/workstationClusters" % client.transport._host, args[1]) - - -def test_list_workstation_clusters_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_clusters( - workstations.ListWorkstationClustersRequest(), - parent='parent_value', - ) - - -def test_list_workstation_clusters_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListWorkstationClustersResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_workstation_clusters(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.WorkstationCluster) - for i in results) - - pages = list(client.list_workstation_clusters(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", [ - workstations.CreateWorkstationClusterRequest, - dict, -]) -def test_create_workstation_cluster_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["workstation_cluster"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - 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_workstation_cluster(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_workstation_cluster_rest_required_fields(request_type=workstations.CreateWorkstationClusterRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["workstation_cluster_id"] = "" - 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 "workstationClusterId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "workstationClusterId" in jsonified_request - assert jsonified_request["workstationClusterId"] == request_init["workstation_cluster_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["workstationClusterId"] = 'workstation_cluster_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_cluster._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", "workstation_cluster_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "workstationClusterId" in jsonified_request - assert jsonified_request["workstationClusterId"] == 'workstation_cluster_id_value' - - client = WorkstationsClient( - 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_workstation_cluster(request) - - expected_params = [ - ( - "workstationClusterId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_workstation_cluster_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_workstation_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("validateOnly", "workstationClusterId", )) & set(("parent", "workstationClusterId", "workstationCluster", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_workstation_cluster_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation_cluster") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.CreateWorkstationClusterRequest.pb(workstations.CreateWorkstationClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.CreateWorkstationClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_workstation_cluster_rest_bad_request(transport: str = 'rest', request_type=workstations.CreateWorkstationClusterRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["workstation_cluster"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the 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_workstation_cluster(request) - - -def test_create_workstation_cluster_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_workstation_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/workstationClusters" % client.transport._host, args[1]) - - -def test_create_workstation_cluster_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_cluster( - workstations.CreateWorkstationClusterRequest(), - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_value', - ) - - -def test_create_workstation_cluster_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationClusterRequest, - dict, -]) -def test_update_workstation_cluster_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} - request_init["workstation_cluster"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - 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_workstation_cluster(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_workstation_cluster_rest_required_fields(request_type=workstations.UpdateWorkstationClusterRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_cluster._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_workstation_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = WorkstationsClient( - 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_workstation_cluster(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_workstation_cluster_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_workstation_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstationCluster", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_workstation_cluster_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation_cluster") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.UpdateWorkstationClusterRequest.pb(workstations.UpdateWorkstationClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.UpdateWorkstationClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_workstation_cluster_rest_bad_request(transport: str = 'rest', request_type=workstations.UpdateWorkstationClusterRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} - request_init["workstation_cluster"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the 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_workstation_cluster(request) - - -def test_update_workstation_cluster_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - 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 = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - workstation_cluster=workstations.WorkstationCluster(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_workstation_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{workstation_cluster.name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) - - -def test_update_workstation_cluster_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_cluster( - workstations.UpdateWorkstationClusterRequest(), - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_workstation_cluster_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationClusterRequest, - dict, -]) -def test_delete_workstation_cluster_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_workstation_cluster(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_workstation_cluster_rest_required_fields(request_type=workstations.DeleteWorkstationClusterRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_cluster._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_workstation_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("etag", "force", "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 = WorkstationsClient( - 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_workstation_cluster(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_workstation_cluster_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_workstation_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("etag", "force", "validateOnly", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_workstation_cluster_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation_cluster") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.DeleteWorkstationClusterRequest.pb(workstations.DeleteWorkstationClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.DeleteWorkstationClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_workstation_cluster_rest_bad_request(transport: str = 'rest', request_type=workstations.DeleteWorkstationClusterRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_workstation_cluster(request) - - -def test_delete_workstation_cluster_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_workstation_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) - - -def test_delete_workstation_cluster_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_cluster( - workstations.DeleteWorkstationClusterRequest(), - name='name_value', - ) - - -def test_delete_workstation_cluster_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationConfigRequest, - dict, -]) -def test_get_workstation_config_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationConfig( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - degraded=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.WorkstationConfig.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_workstation_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.degraded is True - - -def test_get_workstation_config_rest_required_fields(request_type=workstations.GetWorkstationConfigRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_workstation_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # 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 = workstations.WorkstationConfig.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_workstation_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_workstation_config_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_workstation_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_workstation_config_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation_config") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.GetWorkstationConfigRequest.pb(workstations.GetWorkstationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = workstations.WorkstationConfig.to_json(workstations.WorkstationConfig()) - - request = workstations.GetWorkstationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.WorkstationConfig() - - client.get_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_workstation_config_rest_bad_request(transport: str = 'rest', request_type=workstations.GetWorkstationConfigRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_workstation_config(request) - - -def test_get_workstation_config_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.WorkstationConfig.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_workstation_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) - - -def test_get_workstation_config_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_config( - workstations.GetWorkstationConfigRequest(), - name='name_value', - ) - - -def test_get_workstation_config_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationConfigsRequest, - dict, -]) -def test_list_workstation_configs_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListWorkstationConfigsResponse.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_workstation_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workstation_configs_rest_required_fields(request_type=workstations.ListWorkstationConfigsRequest): - transport_class = transports.WorkstationsRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstation_configs._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstation_configs._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # 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 = workstations.ListWorkstationConfigsResponse.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_workstation_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_workstation_configs_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_workstation_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_workstation_configs_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstation_configs") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstation_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListWorkstationConfigsRequest.pb(workstations.ListWorkstationConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = workstations.ListWorkstationConfigsResponse.to_json(workstations.ListWorkstationConfigsResponse()) - - request = workstations.ListWorkstationConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListWorkstationConfigsResponse() - - client.list_workstation_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_workstation_configs_rest_bad_request(transport: str = 'rest', request_type=workstations.ListWorkstationConfigsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_workstation_configs(request) - - -def test_list_workstation_configs_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListWorkstationConfigsResponse.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_workstation_configs(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs" % client.transport._host, args[1]) - - -def test_list_workstation_configs_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_configs( - workstations.ListWorkstationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_workstation_configs_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListWorkstationConfigsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - pager = client.list_workstation_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.WorkstationConfig) - for i in results) - - pages = list(client.list_workstation_configs(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", [ - workstations.ListUsableWorkstationConfigsRequest, - dict, -]) -def test_list_usable_workstation_configs_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListUsableWorkstationConfigsResponse.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_usable_workstation_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_usable_workstation_configs_rest_required_fields(request_type=workstations.ListUsableWorkstationConfigsRequest): - transport_class = transports.WorkstationsRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_usable_workstation_configs._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_usable_workstation_configs._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # 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 = workstations.ListUsableWorkstationConfigsResponse.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_usable_workstation_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_usable_workstation_configs_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_usable_workstation_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_usable_workstation_configs_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_usable_workstation_configs") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_usable_workstation_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListUsableWorkstationConfigsRequest.pb(workstations.ListUsableWorkstationConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = workstations.ListUsableWorkstationConfigsResponse.to_json(workstations.ListUsableWorkstationConfigsResponse()) - - request = workstations.ListUsableWorkstationConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListUsableWorkstationConfigsResponse() - - client.list_usable_workstation_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_usable_workstation_configs_rest_bad_request(transport: str = 'rest', request_type=workstations.ListUsableWorkstationConfigsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_usable_workstation_configs(request) - - -def test_list_usable_workstation_configs_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListUsableWorkstationConfigsResponse.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_usable_workstation_configs(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs:listUsable" % client.transport._host, args[1]) - - -def test_list_usable_workstation_configs_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_usable_workstation_configs( - workstations.ListUsableWorkstationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_usable_workstation_configs_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListUsableWorkstationConfigsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - pager = client.list_usable_workstation_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.WorkstationConfig) - for i in results) - - pages = list(client.list_usable_workstation_configs(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", [ - workstations.CreateWorkstationConfigRequest, - dict, -]) -def test_create_workstation_config_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request_init["workstation_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'enable_nested_virtualization': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792}}, 'persistent_directories': [{'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}, 'mount_path': 'mount_path_value'}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - 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_workstation_config(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_workstation_config_rest_required_fields(request_type=workstations.CreateWorkstationConfigRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["workstation_config_id"] = "" - 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 "workstationConfigId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "workstationConfigId" in jsonified_request - assert jsonified_request["workstationConfigId"] == request_init["workstation_config_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["workstationConfigId"] = 'workstation_config_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_config._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", "workstation_config_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "workstationConfigId" in jsonified_request - assert jsonified_request["workstationConfigId"] == 'workstation_config_id_value' - - client = WorkstationsClient( - 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_workstation_config(request) - - expected_params = [ - ( - "workstationConfigId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_workstation_config_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_workstation_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("validateOnly", "workstationConfigId", )) & set(("parent", "workstationConfigId", "workstationConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_workstation_config_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation_config") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.CreateWorkstationConfigRequest.pb(workstations.CreateWorkstationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.CreateWorkstationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_workstation_config_rest_bad_request(transport: str = 'rest', request_type=workstations.CreateWorkstationConfigRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request_init["workstation_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'enable_nested_virtualization': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792}}, 'persistent_directories': [{'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}, 'mount_path': 'mount_path_value'}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the 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_workstation_config(request) - - -def test_create_workstation_config_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_workstation_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs" % client.transport._host, args[1]) - - -def test_create_workstation_config_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_config( - workstations.CreateWorkstationConfigRequest(), - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_value', - ) - - -def test_create_workstation_config_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationConfigRequest, - dict, -]) -def test_update_workstation_config_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} - request_init["workstation_config"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'enable_nested_virtualization': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792}}, 'persistent_directories': [{'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}, 'mount_path': 'mount_path_value'}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - 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_workstation_config(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_workstation_config_rest_required_fields(request_type=workstations.UpdateWorkstationConfigRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_workstation_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = WorkstationsClient( - 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_workstation_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_workstation_config_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_workstation_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstationConfig", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_workstation_config_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation_config") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.UpdateWorkstationConfigRequest.pb(workstations.UpdateWorkstationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.UpdateWorkstationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_workstation_config_rest_bad_request(transport: str = 'rest', request_type=workstations.UpdateWorkstationConfigRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} - request_init["workstation_config"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'enable_nested_virtualization': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792}}, 'persistent_directories': [{'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}, 'mount_path': 'mount_path_value'}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the 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_workstation_config(request) - - -def test_update_workstation_config_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - 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 = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - workstation_config=workstations.WorkstationConfig(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_workstation_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{workstation_config.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) - - -def test_update_workstation_config_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_config( - workstations.UpdateWorkstationConfigRequest(), - workstation_config=workstations.WorkstationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_workstation_config_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationConfigRequest, - dict, -]) -def test_delete_workstation_config_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = 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_workstation_config(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_workstation_config_rest_required_fields(request_type=workstations.DeleteWorkstationConfigRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_workstation_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("etag", "force", "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 = WorkstationsClient( - 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_workstation_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_workstation_config_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_workstation_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("etag", "force", "validateOnly", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_workstation_config_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation_config") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.DeleteWorkstationConfigRequest.pb(workstations.DeleteWorkstationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.DeleteWorkstationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_workstation_config_rest_bad_request(transport: str = 'rest', request_type=workstations.DeleteWorkstationConfigRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_workstation_config(request) - - -def test_delete_workstation_config_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_workstation_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_workstation_config_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_config( - workstations.DeleteWorkstationConfigRequest(), - name='name_value', - ) - - -def test_delete_workstation_config_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationRequest, - dict, -]) -def test_get_workstation_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.Workstation( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - state=workstations.Workstation.State.STATE_STARTING, - host='host_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.Workstation.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_workstation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.Workstation) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.state == workstations.Workstation.State.STATE_STARTING - assert response.host == 'host_value' - - -def test_get_workstation_rest_required_fields(request_type=workstations.GetWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation._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_workstation._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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.Workstation() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # 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 = workstations.Workstation.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_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.GetWorkstationRequest.pb(workstations.GetWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = workstations.Workstation.to_json(workstations.Workstation()) - - request = workstations.GetWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.Workstation() - - client.get_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.GetWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_workstation(request) - - -def test_get_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.Workstation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.Workstation.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_workstation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) - - -def test_get_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation( - workstations.GetWorkstationRequest(), - name='name_value', - ) - - -def test_get_workstation_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationsRequest, - dict, -]) -def test_list_workstations_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListWorkstationsResponse.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_workstations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workstations_rest_required_fields(request_type=workstations.ListWorkstationsRequest): - transport_class = transports.WorkstationsRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstations._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstations._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # 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 = workstations.ListWorkstationsResponse.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_workstations(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_workstations_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_workstations._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_workstations_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstations") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstations") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListWorkstationsRequest.pb(workstations.ListWorkstationsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = workstations.ListWorkstationsResponse.to_json(workstations.ListWorkstationsResponse()) - - request = workstations.ListWorkstationsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListWorkstationsResponse() - - client.list_workstations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_workstations_rest_bad_request(transport: str = 'rest', request_type=workstations.ListWorkstationsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_workstations(request) - - -def test_list_workstations_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListWorkstationsResponse.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_workstations(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations" % client.transport._host, args[1]) - - -def test_list_workstations_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstations( - workstations.ListWorkstationsRequest(), - parent='parent_value', - ) - - -def test_list_workstations_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListWorkstationsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - pager = client.list_workstations(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.Workstation) - for i in results) - - pages = list(client.list_workstations(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", [ - workstations.ListUsableWorkstationsRequest, - dict, -]) -def test_list_usable_workstations_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListUsableWorkstationsResponse.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_usable_workstations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_usable_workstations_rest_required_fields(request_type=workstations.ListUsableWorkstationsRequest): - transport_class = transports.WorkstationsRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_usable_workstations._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_usable_workstations._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # 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 = workstations.ListUsableWorkstationsResponse.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_usable_workstations(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_usable_workstations_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_usable_workstations._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_usable_workstations_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_usable_workstations") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_usable_workstations") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListUsableWorkstationsRequest.pb(workstations.ListUsableWorkstationsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = workstations.ListUsableWorkstationsResponse.to_json(workstations.ListUsableWorkstationsResponse()) - - request = workstations.ListUsableWorkstationsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListUsableWorkstationsResponse() - - client.list_usable_workstations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_usable_workstations_rest_bad_request(transport: str = 'rest', request_type=workstations.ListUsableWorkstationsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_usable_workstations(request) - - -def test_list_usable_workstations_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListUsableWorkstationsResponse.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_usable_workstations(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations:listUsable" % client.transport._host, args[1]) - - -def test_list_usable_workstations_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_usable_workstations( - workstations.ListUsableWorkstationsRequest(), - parent='parent_value', - ) - - -def test_list_usable_workstations_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListUsableWorkstationsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - pager = client.list_usable_workstations(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.Workstation) - for i in results) - - pages = list(client.list_usable_workstations(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", [ - workstations.CreateWorkstationRequest, - dict, -]) -def test_create_workstation_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request_init["workstation"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_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_workstation(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_workstation_rest_required_fields(request_type=workstations.CreateWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["workstation_id"] = "" - 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 "workstationId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "workstationId" in jsonified_request - assert jsonified_request["workstationId"] == request_init["workstation_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["workstationId"] = 'workstation_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation._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", "workstation_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "workstationId" in jsonified_request - assert jsonified_request["workstationId"] == 'workstation_id_value' - - client = WorkstationsClient( - 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_workstation(request) - - expected_params = [ - ( - "workstationId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(("validateOnly", "workstationId", )) & set(("parent", "workstationId", "workstation", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.CreateWorkstationRequest.pb(workstations.CreateWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.CreateWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.CreateWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request_init["workstation"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_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_workstation(request) - - -def test_create_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_workstation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations" % client.transport._host, args[1]) - - -def test_create_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation( - workstations.CreateWorkstationRequest(), - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_value', - ) - - -def test_create_workstation_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationRequest, - dict, -]) -def test_update_workstation_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} - request_init["workstation"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_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_workstation(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_workstation_rest_required_fields(request_type=workstations.UpdateWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation._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_workstation._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = WorkstationsClient( - 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_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstation", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.UpdateWorkstationRequest.pb(workstations.UpdateWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.UpdateWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.UpdateWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} - request_init["workstation"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_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_workstation(request) - - -def test_update_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - 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 = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} - - # get truthy value for each flattened field - mock_args = dict( - workstation=workstations.Workstation(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_workstation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{workstation.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) - - -def test_update_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation( - workstations.UpdateWorkstationRequest(), - workstation=workstations.Workstation(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_workstation_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationRequest, - dict, -]) -def test_delete_workstation_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = 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_workstation(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_workstation_rest_required_fields(request_type=workstations.DeleteWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation._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_workstation._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 = WorkstationsClient( - 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_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(("etag", "validateOnly", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.DeleteWorkstationRequest.pb(workstations.DeleteWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.DeleteWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.DeleteWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_workstation(request) - - -def test_delete_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_workstation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) - - -def test_delete_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation( - workstations.DeleteWorkstationRequest(), - name='name_value', - ) - - -def test_delete_workstation_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.StartWorkstationRequest, - dict, -]) -def test_start_workstation_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = 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.start_workstation(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_start_workstation_rest_required_fields(request_type=workstations.StartWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - 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()).start_workstation._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()).start_workstation._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 = WorkstationsClient( - 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.start_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_start_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.start_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_start_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_start_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_start_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.StartWorkstationRequest.pb(workstations.StartWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.StartWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.start_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_start_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.StartWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.start_workstation(request) - - -def test_start_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.start_workstation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:start" % client.transport._host, args[1]) - - -def test_start_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.start_workstation( - workstations.StartWorkstationRequest(), - name='name_value', - ) - - -def test_start_workstation_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.StopWorkstationRequest, - dict, -]) -def test_stop_workstation_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = 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.stop_workstation(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_stop_workstation_rest_required_fields(request_type=workstations.StopWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - 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()).stop_workstation._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()).stop_workstation._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 = WorkstationsClient( - 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.stop_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_stop_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.stop_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_stop_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_stop_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_stop_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.StopWorkstationRequest.pb(workstations.StopWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.StopWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.stop_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_stop_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.StopWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.stop_workstation(request) - - -def test_stop_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.stop_workstation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:stop" % client.transport._host, args[1]) - - -def test_stop_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.stop_workstation( - workstations.StopWorkstationRequest(), - name='name_value', - ) - - -def test_stop_workstation_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GenerateAccessTokenRequest, - dict, -]) -def test_generate_access_token_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.GenerateAccessTokenResponse( - access_token='access_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.GenerateAccessTokenResponse.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.generate_access_token(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.GenerateAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -def test_generate_access_token_rest_required_fields(request_type=workstations.GenerateAccessTokenRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["workstation"] = "" - 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()).generate_access_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["workstation"] = 'workstation_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_access_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "workstation" in jsonified_request - assert jsonified_request["workstation"] == 'workstation_value' - - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.GenerateAccessTokenResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # 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 - - pb_return_value = workstations.GenerateAccessTokenResponse.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.generate_access_token(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_generate_access_token_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.generate_access_token._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("workstation", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_access_token_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_generate_access_token") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_generate_access_token") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.GenerateAccessTokenRequest.pb(workstations.GenerateAccessTokenRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = workstations.GenerateAccessTokenResponse.to_json(workstations.GenerateAccessTokenResponse()) - - request = workstations.GenerateAccessTokenRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.GenerateAccessTokenResponse() - - client.generate_access_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_generate_access_token_rest_bad_request(transport: str = 'rest', request_type=workstations.GenerateAccessTokenRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.generate_access_token(request) - - -def test_generate_access_token_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.GenerateAccessTokenResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - workstation='workstation_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 = workstations.GenerateAccessTokenResponse.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.generate_access_token(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{workstation=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:generateAccessToken" % client.transport._host, args[1]) - - -def test_generate_access_token_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.generate_access_token( - workstations.GenerateAccessTokenRequest(), - workstation='workstation_value', - ) - - -def test_generate_access_token_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WorkstationsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = WorkstationsClient( - 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 = WorkstationsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WorkstationsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = WorkstationsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.WorkstationsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.WorkstationsGrpcTransport, - transports.WorkstationsGrpcAsyncIOTransport, - transports.WorkstationsRestTransport, -]) -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 = WorkstationsClient.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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.WorkstationsGrpcTransport, - ) - -def test_workstations_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.WorkstationsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_workstations_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.workstations_v1.services.workstations.transports.WorkstationsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.WorkstationsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_workstation_cluster', - 'list_workstation_clusters', - 'create_workstation_cluster', - 'update_workstation_cluster', - 'delete_workstation_cluster', - 'get_workstation_config', - 'list_workstation_configs', - 'list_usable_workstation_configs', - 'create_workstation_config', - 'update_workstation_config', - 'delete_workstation_config', - 'get_workstation', - 'list_workstations', - 'list_usable_workstations', - 'create_workstation', - 'update_workstation', - 'delete_workstation', - 'start_workstation', - 'stop_workstation', - 'generate_access_token', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - 'get_operation', - 'cancel_operation', - 'delete_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_workstations_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.workstations_v1.services.workstations.transports.WorkstationsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WorkstationsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_workstations_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.workstations_v1.services.workstations.transports.WorkstationsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WorkstationsTransport() - adc.assert_called_once() - - -def test_workstations_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) - WorkstationsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.WorkstationsGrpcTransport, - transports.WorkstationsGrpcAsyncIOTransport, - ], -) -def test_workstations_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.WorkstationsGrpcTransport, - transports.WorkstationsGrpcAsyncIOTransport, - transports.WorkstationsRestTransport, - ], -) -def test_workstations_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.WorkstationsGrpcTransport, grpc_helpers), - (transports.WorkstationsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_workstations_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( - "workstations.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="workstations.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) -def test_workstations_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_workstations_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.WorkstationsRestTransport ( - 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_workstations_rest_lro_client(): - client = WorkstationsClient( - 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_workstations_host_no_port(transport_name): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='workstations.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'workstations.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://workstations.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_workstations_host_with_port(transport_name): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='workstations.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'workstations.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://workstations.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_workstations_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = WorkstationsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = WorkstationsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_workstation_cluster._session - session2 = client2.transport.get_workstation_cluster._session - assert session1 != session2 - session1 = client1.transport.list_workstation_clusters._session - session2 = client2.transport.list_workstation_clusters._session - assert session1 != session2 - session1 = client1.transport.create_workstation_cluster._session - session2 = client2.transport.create_workstation_cluster._session - assert session1 != session2 - session1 = client1.transport.update_workstation_cluster._session - session2 = client2.transport.update_workstation_cluster._session - assert session1 != session2 - session1 = client1.transport.delete_workstation_cluster._session - session2 = client2.transport.delete_workstation_cluster._session - assert session1 != session2 - session1 = client1.transport.get_workstation_config._session - session2 = client2.transport.get_workstation_config._session - assert session1 != session2 - session1 = client1.transport.list_workstation_configs._session - session2 = client2.transport.list_workstation_configs._session - assert session1 != session2 - session1 = client1.transport.list_usable_workstation_configs._session - session2 = client2.transport.list_usable_workstation_configs._session - assert session1 != session2 - session1 = client1.transport.create_workstation_config._session - session2 = client2.transport.create_workstation_config._session - assert session1 != session2 - session1 = client1.transport.update_workstation_config._session - session2 = client2.transport.update_workstation_config._session - assert session1 != session2 - session1 = client1.transport.delete_workstation_config._session - session2 = client2.transport.delete_workstation_config._session - assert session1 != session2 - session1 = client1.transport.get_workstation._session - session2 = client2.transport.get_workstation._session - assert session1 != session2 - session1 = client1.transport.list_workstations._session - session2 = client2.transport.list_workstations._session - assert session1 != session2 - session1 = client1.transport.list_usable_workstations._session - session2 = client2.transport.list_usable_workstations._session - assert session1 != session2 - session1 = client1.transport.create_workstation._session - session2 = client2.transport.create_workstation._session - assert session1 != session2 - session1 = client1.transport.update_workstation._session - session2 = client2.transport.update_workstation._session - assert session1 != session2 - session1 = client1.transport.delete_workstation._session - session2 = client2.transport.delete_workstation._session - assert session1 != session2 - session1 = client1.transport.start_workstation._session - session2 = client2.transport.start_workstation._session - assert session1 != session2 - session1 = client1.transport.stop_workstation._session - session2 = client2.transport.stop_workstation._session - assert session1 != session2 - session1 = client1.transport.generate_access_token._session - session2 = client2.transport.generate_access_token._session - assert session1 != session2 -def test_workstations_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WorkstationsGrpcTransport( - 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_workstations_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WorkstationsGrpcAsyncIOTransport( - 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.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) -def test_workstations_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.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) -def test_workstations_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_workstations_grpc_lro_client(): - client = WorkstationsClient( - 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_workstations_grpc_lro_async_client(): - client = WorkstationsAsyncClient( - 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_workstation_path(): - project = "squid" - location = "clam" - workstation_cluster = "whelk" - workstation_config = "octopus" - workstation = "oyster" - expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}/workstations/{workstation}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, workstation=workstation, ) - actual = WorkstationsClient.workstation_path(project, location, workstation_cluster, workstation_config, workstation) - assert expected == actual - - -def test_parse_workstation_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "workstation_cluster": "mussel", - "workstation_config": "winkle", - "workstation": "nautilus", - } - path = WorkstationsClient.workstation_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_workstation_path(path) - assert expected == actual - -def test_workstation_cluster_path(): - project = "scallop" - location = "abalone" - workstation_cluster = "squid" - expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}".format(project=project, location=location, workstation_cluster=workstation_cluster, ) - actual = WorkstationsClient.workstation_cluster_path(project, location, workstation_cluster) - assert expected == actual - - -def test_parse_workstation_cluster_path(): - expected = { - "project": "clam", - "location": "whelk", - "workstation_cluster": "octopus", - } - path = WorkstationsClient.workstation_cluster_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_workstation_cluster_path(path) - assert expected == actual - -def test_workstation_config_path(): - project = "oyster" - location = "nudibranch" - workstation_cluster = "cuttlefish" - workstation_config = "mussel" - expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, ) - actual = WorkstationsClient.workstation_config_path(project, location, workstation_cluster, workstation_config) - assert expected == actual - - -def test_parse_workstation_config_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "workstation_cluster": "scallop", - "workstation_config": "abalone", - } - path = WorkstationsClient.workstation_config_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_workstation_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = WorkstationsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = WorkstationsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = WorkstationsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = WorkstationsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = WorkstationsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = WorkstationsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = WorkstationsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = WorkstationsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = WorkstationsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = WorkstationsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.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.WorkstationsTransport, '_prep_wrapped_messages') as prep: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.WorkstationsTransport, '_prep_wrapped_messages') as prep: - transport_class = WorkstationsClient.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 = WorkstationsAsyncClient( - 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_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_delete_operation(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_delete_operation_async(transport: str = "grpc"): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_operation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = None - - client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_delete_operation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_delete_operation_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_delete_operation_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_cancel_operation(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - response = client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - response = await client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - -def test_set_iam_policy_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - -def test_set_iam_policy_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -@pytest.mark.asyncio -async def test_set_iam_policy_from_dict_async(): - client = WorkstationsAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - -def test_get_iam_policy(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_get_iam_policy_from_dict_async(): - client = WorkstationsAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -def test_test_iam_permissions(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) - ) - - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - response = client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_test_iam_permissions_from_dict_async(): - client = WorkstationsAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = WorkstationsClient( - 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 = WorkstationsClient( - 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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/.coveragerc b/owl-bot-staging/google-cloud-workstations/v1beta/.coveragerc deleted file mode 100644 index ee1a17c3e2ca..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/workstations/__init__.py - google/cloud/workstations/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/.flake8 b/owl-bot-staging/google-cloud-workstations/v1beta/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/MANIFEST.in b/owl-bot-staging/google-cloud-workstations/v1beta/MANIFEST.in deleted file mode 100644 index ebef07fddb1d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/workstations *.py -recursive-include google/cloud/workstations_v1beta *.py diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/README.rst b/owl-bot-staging/google-cloud-workstations/v1beta/README.rst deleted file mode 100644 index 48a711be018f..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Workstations 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 Workstations API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/docs/conf.py b/owl-bot-staging/google-cloud-workstations/v1beta/docs/conf.py deleted file mode 100644 index 06f3a6eac397..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-workstations 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-workstations" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = 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-workstations-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-workstations.tex", - u"google-cloud-workstations 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-workstations", - u"Google Cloud Workstations 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-workstations", - u"google-cloud-workstations Documentation", - author, - "google-cloud-workstations", - "GAPIC library for Google Cloud Workstations API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/docs/index.rst b/owl-bot-staging/google-cloud-workstations/v1beta/docs/index.rst deleted file mode 100644 index 4454f94e00e1..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - workstations_v1beta/services - workstations_v1beta/types diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/services.rst b/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/services.rst deleted file mode 100644 index 77aed9f52d7a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Workstations v1beta API -================================================= -.. toctree:: - :maxdepth: 2 - - workstations diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/types.rst b/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/types.rst deleted file mode 100644 index af7f36fbcb60..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Workstations v1beta API -============================================== - -.. automodule:: google.cloud.workstations_v1beta.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/workstations.rst b/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/workstations.rst deleted file mode 100644 index 5839880c918a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/docs/workstations_v1beta/workstations.rst +++ /dev/null @@ -1,10 +0,0 @@ -Workstations ------------------------------- - -.. automodule:: google.cloud.workstations_v1beta.services.workstations - :members: - :inherited-members: - -.. automodule:: google.cloud.workstations_v1beta.services.workstations.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/__init__.py deleted file mode 100644 index 7876f1ab4d1a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/__init__.py +++ /dev/null @@ -1,87 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.workstations import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.workstations_v1beta.services.workstations.client import WorkstationsClient -from google.cloud.workstations_v1beta.services.workstations.async_client import WorkstationsAsyncClient - -from google.cloud.workstations_v1beta.types.workstations import CreateWorkstationClusterRequest -from google.cloud.workstations_v1beta.types.workstations import CreateWorkstationConfigRequest -from google.cloud.workstations_v1beta.types.workstations import CreateWorkstationRequest -from google.cloud.workstations_v1beta.types.workstations import DeleteWorkstationClusterRequest -from google.cloud.workstations_v1beta.types.workstations import DeleteWorkstationConfigRequest -from google.cloud.workstations_v1beta.types.workstations import DeleteWorkstationRequest -from google.cloud.workstations_v1beta.types.workstations import GenerateAccessTokenRequest -from google.cloud.workstations_v1beta.types.workstations import GenerateAccessTokenResponse -from google.cloud.workstations_v1beta.types.workstations import GetWorkstationClusterRequest -from google.cloud.workstations_v1beta.types.workstations import GetWorkstationConfigRequest -from google.cloud.workstations_v1beta.types.workstations import GetWorkstationRequest -from google.cloud.workstations_v1beta.types.workstations import ListUsableWorkstationConfigsRequest -from google.cloud.workstations_v1beta.types.workstations import ListUsableWorkstationConfigsResponse -from google.cloud.workstations_v1beta.types.workstations import ListUsableWorkstationsRequest -from google.cloud.workstations_v1beta.types.workstations import ListUsableWorkstationsResponse -from google.cloud.workstations_v1beta.types.workstations import ListWorkstationClustersRequest -from google.cloud.workstations_v1beta.types.workstations import ListWorkstationClustersResponse -from google.cloud.workstations_v1beta.types.workstations import ListWorkstationConfigsRequest -from google.cloud.workstations_v1beta.types.workstations import ListWorkstationConfigsResponse -from google.cloud.workstations_v1beta.types.workstations import ListWorkstationsRequest -from google.cloud.workstations_v1beta.types.workstations import ListWorkstationsResponse -from google.cloud.workstations_v1beta.types.workstations import OperationMetadata -from google.cloud.workstations_v1beta.types.workstations import StartWorkstationRequest -from google.cloud.workstations_v1beta.types.workstations import StopWorkstationRequest -from google.cloud.workstations_v1beta.types.workstations import UpdateWorkstationClusterRequest -from google.cloud.workstations_v1beta.types.workstations import UpdateWorkstationConfigRequest -from google.cloud.workstations_v1beta.types.workstations import UpdateWorkstationRequest -from google.cloud.workstations_v1beta.types.workstations import Workstation -from google.cloud.workstations_v1beta.types.workstations import WorkstationCluster -from google.cloud.workstations_v1beta.types.workstations import WorkstationConfig - -__all__ = ('WorkstationsClient', - 'WorkstationsAsyncClient', - 'CreateWorkstationClusterRequest', - 'CreateWorkstationConfigRequest', - 'CreateWorkstationRequest', - 'DeleteWorkstationClusterRequest', - 'DeleteWorkstationConfigRequest', - 'DeleteWorkstationRequest', - 'GenerateAccessTokenRequest', - 'GenerateAccessTokenResponse', - 'GetWorkstationClusterRequest', - 'GetWorkstationConfigRequest', - 'GetWorkstationRequest', - 'ListUsableWorkstationConfigsRequest', - 'ListUsableWorkstationConfigsResponse', - 'ListUsableWorkstationsRequest', - 'ListUsableWorkstationsResponse', - 'ListWorkstationClustersRequest', - 'ListWorkstationClustersResponse', - 'ListWorkstationConfigsRequest', - 'ListWorkstationConfigsResponse', - 'ListWorkstationsRequest', - 'ListWorkstationsResponse', - 'OperationMetadata', - 'StartWorkstationRequest', - 'StopWorkstationRequest', - 'UpdateWorkstationClusterRequest', - 'UpdateWorkstationConfigRequest', - 'UpdateWorkstationRequest', - 'Workstation', - 'WorkstationCluster', - 'WorkstationConfig', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/gapic_version.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/gapic_version.py deleted file mode 100644 index 360a0d13ebdd..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/py.typed b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/py.typed deleted file mode 100644 index 04170223dff9..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-workstations package uses inline types. diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/__init__.py deleted file mode 100644 index ef2969955daf..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/__init__.py +++ /dev/null @@ -1,88 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.workstations_v1beta import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.workstations import WorkstationsClient -from .services.workstations import WorkstationsAsyncClient - -from .types.workstations import CreateWorkstationClusterRequest -from .types.workstations import CreateWorkstationConfigRequest -from .types.workstations import CreateWorkstationRequest -from .types.workstations import DeleteWorkstationClusterRequest -from .types.workstations import DeleteWorkstationConfigRequest -from .types.workstations import DeleteWorkstationRequest -from .types.workstations import GenerateAccessTokenRequest -from .types.workstations import GenerateAccessTokenResponse -from .types.workstations import GetWorkstationClusterRequest -from .types.workstations import GetWorkstationConfigRequest -from .types.workstations import GetWorkstationRequest -from .types.workstations import ListUsableWorkstationConfigsRequest -from .types.workstations import ListUsableWorkstationConfigsResponse -from .types.workstations import ListUsableWorkstationsRequest -from .types.workstations import ListUsableWorkstationsResponse -from .types.workstations import ListWorkstationClustersRequest -from .types.workstations import ListWorkstationClustersResponse -from .types.workstations import ListWorkstationConfigsRequest -from .types.workstations import ListWorkstationConfigsResponse -from .types.workstations import ListWorkstationsRequest -from .types.workstations import ListWorkstationsResponse -from .types.workstations import OperationMetadata -from .types.workstations import StartWorkstationRequest -from .types.workstations import StopWorkstationRequest -from .types.workstations import UpdateWorkstationClusterRequest -from .types.workstations import UpdateWorkstationConfigRequest -from .types.workstations import UpdateWorkstationRequest -from .types.workstations import Workstation -from .types.workstations import WorkstationCluster -from .types.workstations import WorkstationConfig - -__all__ = ( - 'WorkstationsAsyncClient', -'CreateWorkstationClusterRequest', -'CreateWorkstationConfigRequest', -'CreateWorkstationRequest', -'DeleteWorkstationClusterRequest', -'DeleteWorkstationConfigRequest', -'DeleteWorkstationRequest', -'GenerateAccessTokenRequest', -'GenerateAccessTokenResponse', -'GetWorkstationClusterRequest', -'GetWorkstationConfigRequest', -'GetWorkstationRequest', -'ListUsableWorkstationConfigsRequest', -'ListUsableWorkstationConfigsResponse', -'ListUsableWorkstationsRequest', -'ListUsableWorkstationsResponse', -'ListWorkstationClustersRequest', -'ListWorkstationClustersResponse', -'ListWorkstationConfigsRequest', -'ListWorkstationConfigsResponse', -'ListWorkstationsRequest', -'ListWorkstationsResponse', -'OperationMetadata', -'StartWorkstationRequest', -'StopWorkstationRequest', -'UpdateWorkstationClusterRequest', -'UpdateWorkstationConfigRequest', -'UpdateWorkstationRequest', -'Workstation', -'WorkstationCluster', -'WorkstationConfig', -'WorkstationsClient', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_metadata.json b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_metadata.json deleted file mode 100644 index cf8a80968ec1..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_metadata.json +++ /dev/null @@ -1,328 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.workstations_v1beta", - "protoPackage": "google.cloud.workstations.v1beta", - "schema": "1.0", - "services": { - "Workstations": { - "clients": { - "grpc": { - "libraryClient": "WorkstationsClient", - "rpcs": { - "CreateWorkstation": { - "methods": [ - "create_workstation" - ] - }, - "CreateWorkstationCluster": { - "methods": [ - "create_workstation_cluster" - ] - }, - "CreateWorkstationConfig": { - "methods": [ - "create_workstation_config" - ] - }, - "DeleteWorkstation": { - "methods": [ - "delete_workstation" - ] - }, - "DeleteWorkstationCluster": { - "methods": [ - "delete_workstation_cluster" - ] - }, - "DeleteWorkstationConfig": { - "methods": [ - "delete_workstation_config" - ] - }, - "GenerateAccessToken": { - "methods": [ - "generate_access_token" - ] - }, - "GetWorkstation": { - "methods": [ - "get_workstation" - ] - }, - "GetWorkstationCluster": { - "methods": [ - "get_workstation_cluster" - ] - }, - "GetWorkstationConfig": { - "methods": [ - "get_workstation_config" - ] - }, - "ListUsableWorkstationConfigs": { - "methods": [ - "list_usable_workstation_configs" - ] - }, - "ListUsableWorkstations": { - "methods": [ - "list_usable_workstations" - ] - }, - "ListWorkstationClusters": { - "methods": [ - "list_workstation_clusters" - ] - }, - "ListWorkstationConfigs": { - "methods": [ - "list_workstation_configs" - ] - }, - "ListWorkstations": { - "methods": [ - "list_workstations" - ] - }, - "StartWorkstation": { - "methods": [ - "start_workstation" - ] - }, - "StopWorkstation": { - "methods": [ - "stop_workstation" - ] - }, - "UpdateWorkstation": { - "methods": [ - "update_workstation" - ] - }, - "UpdateWorkstationCluster": { - "methods": [ - "update_workstation_cluster" - ] - }, - "UpdateWorkstationConfig": { - "methods": [ - "update_workstation_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "WorkstationsAsyncClient", - "rpcs": { - "CreateWorkstation": { - "methods": [ - "create_workstation" - ] - }, - "CreateWorkstationCluster": { - "methods": [ - "create_workstation_cluster" - ] - }, - "CreateWorkstationConfig": { - "methods": [ - "create_workstation_config" - ] - }, - "DeleteWorkstation": { - "methods": [ - "delete_workstation" - ] - }, - "DeleteWorkstationCluster": { - "methods": [ - "delete_workstation_cluster" - ] - }, - "DeleteWorkstationConfig": { - "methods": [ - "delete_workstation_config" - ] - }, - "GenerateAccessToken": { - "methods": [ - "generate_access_token" - ] - }, - "GetWorkstation": { - "methods": [ - "get_workstation" - ] - }, - "GetWorkstationCluster": { - "methods": [ - "get_workstation_cluster" - ] - }, - "GetWorkstationConfig": { - "methods": [ - "get_workstation_config" - ] - }, - "ListUsableWorkstationConfigs": { - "methods": [ - "list_usable_workstation_configs" - ] - }, - "ListUsableWorkstations": { - "methods": [ - "list_usable_workstations" - ] - }, - "ListWorkstationClusters": { - "methods": [ - "list_workstation_clusters" - ] - }, - "ListWorkstationConfigs": { - "methods": [ - "list_workstation_configs" - ] - }, - "ListWorkstations": { - "methods": [ - "list_workstations" - ] - }, - "StartWorkstation": { - "methods": [ - "start_workstation" - ] - }, - "StopWorkstation": { - "methods": [ - "stop_workstation" - ] - }, - "UpdateWorkstation": { - "methods": [ - "update_workstation" - ] - }, - "UpdateWorkstationCluster": { - "methods": [ - "update_workstation_cluster" - ] - }, - "UpdateWorkstationConfig": { - "methods": [ - "update_workstation_config" - ] - } - } - }, - "rest": { - "libraryClient": "WorkstationsClient", - "rpcs": { - "CreateWorkstation": { - "methods": [ - "create_workstation" - ] - }, - "CreateWorkstationCluster": { - "methods": [ - "create_workstation_cluster" - ] - }, - "CreateWorkstationConfig": { - "methods": [ - "create_workstation_config" - ] - }, - "DeleteWorkstation": { - "methods": [ - "delete_workstation" - ] - }, - "DeleteWorkstationCluster": { - "methods": [ - "delete_workstation_cluster" - ] - }, - "DeleteWorkstationConfig": { - "methods": [ - "delete_workstation_config" - ] - }, - "GenerateAccessToken": { - "methods": [ - "generate_access_token" - ] - }, - "GetWorkstation": { - "methods": [ - "get_workstation" - ] - }, - "GetWorkstationCluster": { - "methods": [ - "get_workstation_cluster" - ] - }, - "GetWorkstationConfig": { - "methods": [ - "get_workstation_config" - ] - }, - "ListUsableWorkstationConfigs": { - "methods": [ - "list_usable_workstation_configs" - ] - }, - "ListUsableWorkstations": { - "methods": [ - "list_usable_workstations" - ] - }, - "ListWorkstationClusters": { - "methods": [ - "list_workstation_clusters" - ] - }, - "ListWorkstationConfigs": { - "methods": [ - "list_workstation_configs" - ] - }, - "ListWorkstations": { - "methods": [ - "list_workstations" - ] - }, - "StartWorkstation": { - "methods": [ - "start_workstation" - ] - }, - "StopWorkstation": { - "methods": [ - "stop_workstation" - ] - }, - "UpdateWorkstation": { - "methods": [ - "update_workstation" - ] - }, - "UpdateWorkstationCluster": { - "methods": [ - "update_workstation_cluster" - ] - }, - "UpdateWorkstationConfig": { - "methods": [ - "update_workstation_config" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_version.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_version.py deleted file mode 100644 index 360a0d13ebdd..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/py.typed b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/py.typed deleted file mode 100644 index 04170223dff9..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-workstations package uses inline types. diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/__init__.py deleted file mode 100644 index 89a37dc92c5a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/__init__.py deleted file mode 100644 index 0d8e475505ba..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 WorkstationsClient -from .async_client import WorkstationsAsyncClient - -__all__ = ( - 'WorkstationsClient', - 'WorkstationsAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/async_client.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/async_client.py deleted file mode 100644 index f502c173f6a2..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/async_client.py +++ /dev/null @@ -1,3093 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.workstations_v1beta 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.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1beta.services.workstations import pagers -from google.cloud.workstations_v1beta.types import workstations -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 -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import WorkstationsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import WorkstationsGrpcAsyncIOTransport -from .client import WorkstationsClient - - -class WorkstationsAsyncClient: - """Service for interacting with Cloud Workstations.""" - - _client: WorkstationsClient - - DEFAULT_ENDPOINT = WorkstationsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = WorkstationsClient.DEFAULT_MTLS_ENDPOINT - - workstation_path = staticmethod(WorkstationsClient.workstation_path) - parse_workstation_path = staticmethod(WorkstationsClient.parse_workstation_path) - workstation_cluster_path = staticmethod(WorkstationsClient.workstation_cluster_path) - parse_workstation_cluster_path = staticmethod(WorkstationsClient.parse_workstation_cluster_path) - workstation_config_path = staticmethod(WorkstationsClient.workstation_config_path) - parse_workstation_config_path = staticmethod(WorkstationsClient.parse_workstation_config_path) - common_billing_account_path = staticmethod(WorkstationsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(WorkstationsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(WorkstationsClient.common_folder_path) - parse_common_folder_path = staticmethod(WorkstationsClient.parse_common_folder_path) - common_organization_path = staticmethod(WorkstationsClient.common_organization_path) - parse_common_organization_path = staticmethod(WorkstationsClient.parse_common_organization_path) - common_project_path = staticmethod(WorkstationsClient.common_project_path) - parse_common_project_path = staticmethod(WorkstationsClient.parse_common_project_path) - common_location_path = staticmethod(WorkstationsClient.common_location_path) - parse_common_location_path = staticmethod(WorkstationsClient.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: - WorkstationsAsyncClient: The constructed client. - """ - return WorkstationsClient.from_service_account_info.__func__(WorkstationsAsyncClient, 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: - WorkstationsAsyncClient: The constructed client. - """ - return WorkstationsClient.from_service_account_file.__func__(WorkstationsAsyncClient, 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 WorkstationsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> WorkstationsTransport: - """Returns the transport used by the client instance. - - Returns: - WorkstationsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(WorkstationsClient).get_transport_class, type(WorkstationsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, WorkstationsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the workstations 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, ~.WorkstationsTransport]): 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 = WorkstationsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_workstation_cluster(self, - request: Optional[Union[workstations.GetWorkstationClusterRequest, 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]] = (), - ) -> workstations.WorkstationCluster: - r"""Returns the requested workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_get_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation_cluster(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.GetWorkstationClusterRequest, dict]]): - The request object. Request message for - GetWorkstationCluster. - name (:class:`str`): - Required. Name of the requested - resource. - - 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.workstations_v1beta.types.WorkstationCluster: - A grouping of workstation - configurations and the associated - workstations in that region. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = workstations.GetWorkstationClusterRequest(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_workstation_cluster, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_workstation_clusters(self, - request: Optional[Union[workstations.ListWorkstationClustersRequest, 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.ListWorkstationClustersAsyncPager: - r"""Returns all workstation clusters in the specified - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_list_workstation_clusters(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_clusters(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest, dict]]): - The request object. Request message for - ListWorkstationClusters. - parent (:class:`str`): - Required. Parent resource name. - 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.workstations_v1beta.services.workstations.pagers.ListWorkstationClustersAsyncPager: - Response message for - ListWorkstationClusters. - 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 = workstations.ListWorkstationClustersRequest(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_workstation_clusters, - default_retry=retries.Retry( -initial=1.0,maximum=10.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(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListWorkstationClustersAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_workstation_cluster(self, - request: Optional[Union[workstations.CreateWorkstationClusterRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation_cluster: Optional[workstations.WorkstationCluster] = None, - workstation_cluster_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_create_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationClusterRequest( - parent="parent_value", - workstation_cluster_id="workstation_cluster_id_value", - ) - - # Make the request - operation = client.create_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.CreateWorkstationClusterRequest, dict]]): - The request object. Message for creating a - CreateWorkstationCluster. - parent (:class:`str`): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_cluster (:class:`google.cloud.workstations_v1beta.types.WorkstationCluster`): - Required. Workstation cluster to - create. - - This corresponds to the ``workstation_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_cluster_id (:class:`str`): - Required. ID to use for the - workstation cluster. - - This corresponds to the ``workstation_cluster_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.workstations_v1beta.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations - in that region. - - """ - # Create or coerce a protobuf request object. - # Quick 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, workstation_cluster, workstation_cluster_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = workstations.CreateWorkstationClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation_cluster is not None: - request.workstation_cluster = workstation_cluster - if workstation_cluster_id is not None: - request.workstation_cluster_id = workstation_cluster_id - - # 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_workstation_cluster, - 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(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_workstation_cluster(self, - request: Optional[Union[workstations.UpdateWorkstationClusterRequest, dict]] = None, - *, - workstation_cluster: Optional[workstations.WorkstationCluster] = 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 an existing workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_update_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationClusterRequest( - ) - - # Make the request - operation = client.update_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.UpdateWorkstationClusterRequest, dict]]): - The request object. Request message for - UpdateWorkstationCluster. - workstation_cluster (:class:`google.cloud.workstations_v1beta.types.WorkstationCluster`): - Required. Workstation cluster to - update. - - This corresponds to the ``workstation_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Mask that specifies which - fields in the workstation cluster should - 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.workstations_v1beta.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations - in that region. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation_cluster, 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 = workstations.UpdateWorkstationClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation_cluster is not None: - request.workstation_cluster = workstation_cluster - 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_workstation_cluster, - 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(( - ("workstation_cluster.name", request.workstation_cluster.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, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_workstation_cluster(self, - request: Optional[Union[workstations.DeleteWorkstationClusterRequest, 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 the specified workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_delete_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.DeleteWorkstationClusterRequest, dict]]): - The request object. Message for deleting a workstation - cluster. - name (:class:`str`): - Required. Name of the workstation - cluster to delete. - - 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.workstations_v1beta.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations - in that region. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = workstations.DeleteWorkstationClusterRequest(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_workstation_cluster, - 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, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_workstation_config(self, - request: Optional[Union[workstations.GetWorkstationConfigRequest, 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]] = (), - ) -> workstations.WorkstationConfig: - r"""Returns the requested workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_get_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.GetWorkstationConfigRequest, dict]]): - The request object. Request message for - GetWorkstationConfig. - name (:class:`str`): - Required. Name of the requested - resource. - - 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.workstations_v1beta.types.WorkstationConfig: - A set of configuration options - describing how a workstation will be - run. Workstation configurations are - intended to be shared across multiple - workstations. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = workstations.GetWorkstationConfigRequest(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_workstation_config, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_workstation_configs(self, - request: Optional[Union[workstations.ListWorkstationConfigsRequest, 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.ListWorkstationConfigsAsyncPager: - r"""Returns all workstation configurations in the - specified cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_list_workstation_configs(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest, dict]]): - The request object. Request message for - ListWorkstationConfigs. - parent (:class:`str`): - Required. Parent resource name. - 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.workstations_v1beta.services.workstations.pagers.ListWorkstationConfigsAsyncPager: - Response message for - ListWorkstationConfigs. - 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 = workstations.ListWorkstationConfigsRequest(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_workstation_configs, - default_retry=retries.Retry( -initial=1.0,maximum=10.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(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListWorkstationConfigsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_usable_workstation_configs(self, - request: Optional[Union[workstations.ListUsableWorkstationConfigsRequest, 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.ListUsableWorkstationConfigsAsyncPager: - r"""Returns all workstation configurations in the - specified cluster on which the caller has the - "workstations.workstation.create" permission. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_list_usable_workstation_configs(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListUsableWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstation_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest, dict]]): - The request object. Request message for - ListUsableWorkstationConfigs. - parent (:class:`str`): - Required. Parent resource name. - 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.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationConfigsAsyncPager: - Response message for - ListUsableWorkstationConfigs. - 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 = workstations.ListUsableWorkstationConfigsRequest(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_usable_workstation_configs, - default_retry=retries.Retry( -initial=1.0,maximum=10.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(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListUsableWorkstationConfigsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_workstation_config(self, - request: Optional[Union[workstations.CreateWorkstationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation_config: Optional[workstations.WorkstationConfig] = None, - workstation_config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_create_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationConfigRequest( - parent="parent_value", - workstation_config_id="workstation_config_id_value", - ) - - # Make the request - operation = client.create_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.CreateWorkstationConfigRequest, dict]]): - The request object. Message for creating a - CreateWorkstationConfig. - parent (:class:`str`): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_config (:class:`google.cloud.workstations_v1beta.types.WorkstationConfig`): - Required. Config to create. - This corresponds to the ``workstation_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_config_id (:class:`str`): - Required. ID to use for the - workstation configuration. - - This corresponds to the ``workstation_config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.workstations_v1beta.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. - Workstation configurations are intended to be shared - across multiple workstations. - - """ - # Create or coerce a protobuf request object. - # Quick 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, workstation_config, workstation_config_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = workstations.CreateWorkstationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation_config is not None: - request.workstation_config = workstation_config - if workstation_config_id is not None: - request.workstation_config_id = workstation_config_id - - # 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_workstation_config, - 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(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_workstation_config(self, - request: Optional[Union[workstations.UpdateWorkstationConfigRequest, dict]] = None, - *, - workstation_config: Optional[workstations.WorkstationConfig] = 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 an existing workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_update_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationConfigRequest( - ) - - # Make the request - operation = client.update_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.UpdateWorkstationConfigRequest, dict]]): - The request object. Request message for - UpdateWorkstationConfig. - workstation_config (:class:`google.cloud.workstations_v1beta.types.WorkstationConfig`): - Required. Config to update. - This corresponds to the ``workstation_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Mask specifying which - fields in the workstation configuration - should 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.workstations_v1beta.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. - Workstation configurations are intended to be shared - across multiple workstations. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = workstations.UpdateWorkstationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation_config is not None: - request.workstation_config = workstation_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_workstation_config, - 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(( - ("workstation_config.name", request.workstation_config.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, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_workstation_config(self, - request: Optional[Union[workstations.DeleteWorkstationConfigRequest, 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 the specified workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_delete_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.DeleteWorkstationConfigRequest, dict]]): - The request object. Message for deleting a workstation - configuration. - name (:class:`str`): - Required. Name of the workstation - configuration to delete. - - 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.workstations_v1beta.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. - Workstation configurations are intended to be shared - across multiple workstations. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = workstations.DeleteWorkstationConfigRequest(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_workstation_config, - 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, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_workstation(self, - request: Optional[Union[workstations.GetWorkstationRequest, 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]] = (), - ) -> workstations.Workstation: - r"""Returns the requested workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_get_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.GetWorkstationRequest, dict]]): - The request object. Request message for GetWorkstation. - name (:class:`str`): - Required. Name of the requested - resource. - - 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.workstations_v1beta.types.Workstation: - A single instance of a developer - workstation with its own persistent - storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = workstations.GetWorkstationRequest(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_workstation, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_workstations(self, - request: Optional[Union[workstations.ListWorkstationsRequest, 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.ListWorkstationsAsyncPager: - r"""Returns all Workstations using the specified - workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_list_workstations(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstations(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.ListWorkstationsRequest, dict]]): - The request object. Request message for ListWorkstations. - parent (:class:`str`): - Required. Parent resource name. - 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.workstations_v1beta.services.workstations.pagers.ListWorkstationsAsyncPager: - Response message for - ListWorkstations. - 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 = workstations.ListWorkstationsRequest(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_workstations, - default_retry=retries.Retry( -initial=1.0,maximum=10.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(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListWorkstationsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_usable_workstations(self, - request: Optional[Union[workstations.ListUsableWorkstationsRequest, 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.ListUsableWorkstationsAsyncPager: - r"""Returns all workstations using the specified - workstation configuration on which the caller has the - "workstations.workstations.use" permission. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_list_usable_workstations(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListUsableWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstations(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest, dict]]): - The request object. Request message for - ListUsableWorkstations. - parent (:class:`str`): - Required. Parent resource name. - 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.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationsAsyncPager: - Response message for - ListUsableWorkstations. - 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 = workstations.ListUsableWorkstationsRequest(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_usable_workstations, - default_retry=retries.Retry( -initial=1.0,maximum=10.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(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListUsableWorkstationsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_workstation(self, - request: Optional[Union[workstations.CreateWorkstationRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation: Optional[workstations.Workstation] = None, - workstation_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_create_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationRequest( - parent="parent_value", - workstation_id="workstation_id_value", - ) - - # Make the request - operation = client.create_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.CreateWorkstationRequest, dict]]): - The request object. Message for creating a - CreateWorkstation. - parent (:class:`str`): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation (:class:`google.cloud.workstations_v1beta.types.Workstation`): - Required. Workstation to create. - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_id (:class:`str`): - Required. ID to use for the - workstation. - - This corresponds to the ``workstation_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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, workstation, workstation_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = workstations.CreateWorkstationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation is not None: - request.workstation = workstation - if workstation_id is not None: - request.workstation_id = workstation_id - - # 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_workstation, - 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(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_workstation(self, - request: Optional[Union[workstations.UpdateWorkstationRequest, dict]] = None, - *, - workstation: Optional[workstations.Workstation] = 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 an existing workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_update_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationRequest( - ) - - # Make the request - operation = client.update_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.UpdateWorkstationRequest, dict]]): - The request object. Request message for - UpdateWorkstation. - workstation (:class:`google.cloud.workstations_v1beta.types.Workstation`): - Required. Workstation to update. - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Mask specifying which - fields in the workstation configuration - should 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.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation, 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 = workstations.UpdateWorkstationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation is not None: - request.workstation = workstation - 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_workstation, - 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(( - ("workstation.name", request.workstation.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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_workstation(self, - request: Optional[Union[workstations.DeleteWorkstationRequest, 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 the specified workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_delete_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.DeleteWorkstationRequest, dict]]): - The request object. Request message for - DeleteWorkstation. - name (:class:`str`): - Required. Name of the workstation to - delete. - - 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.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = workstations.DeleteWorkstationRequest(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_workstation, - 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def start_workstation(self, - request: Optional[Union[workstations.StartWorkstationRequest, 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"""Starts running a workstation so that users can - connect to 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 workstations_v1beta - - async def sample_start_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.StartWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.start_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.StartWorkstationRequest, dict]]): - The request object. Request message for StartWorkstation. - name (:class:`str`): - Required. Name of the workstation to - start. - - 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.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = workstations.StartWorkstationRequest(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.start_workstation, - 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def stop_workstation(self, - request: Optional[Union[workstations.StopWorkstationRequest, 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"""Stops running a workstation, reducing costs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_stop_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.StopWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.stop_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.StopWorkstationRequest, dict]]): - The request object. Request message for StopWorkstation. - name (:class:`str`): - Required. Name of the workstation to - stop. - - 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.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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 = workstations.StopWorkstationRequest(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.stop_workstation, - 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def generate_access_token(self, - request: Optional[Union[workstations.GenerateAccessTokenRequest, dict]] = None, - *, - workstation: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.GenerateAccessTokenResponse: - r"""Returns a short-lived credential that can be used to - send authenticated and authorized traffic to a - workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - async def sample_generate_access_token(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.GenerateAccessTokenRequest( - workstation="workstation_value", - ) - - # Make the request - response = await client.generate_access_token(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.workstations_v1beta.types.GenerateAccessTokenRequest, dict]]): - The request object. Request message for - GenerateAccessToken. - workstation (:class:`str`): - Required. Name of the workstation for - which the access token should be - generated. - - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1beta.types.GenerateAccessTokenResponse: - Response message for - GenerateAccessToken. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation]) - if request is 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 = workstations.GenerateAccessTokenRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation is not None: - request.workstation = workstation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.generate_access_token, - default_retry=retries.Retry( -initial=1.0,maximum=10.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(( - ("workstation", request.workstation), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._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) -> "WorkstationsAsyncClient": - 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__ = ( - "WorkstationsAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/client.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/client.py deleted file mode 100644 index 8406e4c3e182..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/client.py +++ /dev/null @@ -1,3259 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.workstations_v1beta 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.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1beta.services.workstations import pagers -from google.cloud.workstations_v1beta.types import workstations -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 -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import WorkstationsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import WorkstationsGrpcTransport -from .transports.grpc_asyncio import WorkstationsGrpcAsyncIOTransport -from .transports.rest import WorkstationsRestTransport - - -class WorkstationsClientMeta(type): - """Metaclass for the Workstations 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[WorkstationsTransport]] - _transport_registry["grpc"] = WorkstationsGrpcTransport - _transport_registry["grpc_asyncio"] = WorkstationsGrpcAsyncIOTransport - _transport_registry["rest"] = WorkstationsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[WorkstationsTransport]: - """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 WorkstationsClient(metaclass=WorkstationsClientMeta): - """Service for interacting with Cloud Workstations.""" - - @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 = "workstations.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: - WorkstationsClient: 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: - WorkstationsClient: 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) -> WorkstationsTransport: - """Returns the transport used by the client instance. - - Returns: - WorkstationsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def workstation_path(project: str,location: str,workstation_cluster: str,workstation_config: str,workstation: str,) -> str: - """Returns a fully-qualified workstation string.""" - return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}/workstations/{workstation}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, workstation=workstation, ) - - @staticmethod - def parse_workstation_path(path: str) -> Dict[str,str]: - """Parses a workstation path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)/workstationConfigs/(?P.+?)/workstations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def workstation_cluster_path(project: str,location: str,workstation_cluster: str,) -> str: - """Returns a fully-qualified workstation_cluster string.""" - return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}".format(project=project, location=location, workstation_cluster=workstation_cluster, ) - - @staticmethod - def parse_workstation_cluster_path(path: str) -> Dict[str,str]: - """Parses a workstation_cluster path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def workstation_config_path(project: str,location: str,workstation_cluster: str,workstation_config: str,) -> str: - """Returns a fully-qualified workstation_config string.""" - return "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, ) - - @staticmethod - def parse_workstation_config_path(path: str) -> Dict[str,str]: - """Parses a workstation_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workstationClusters/(?P.+?)/workstationConfigs/(?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, WorkstationsTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the workstations 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, WorkstationsTransport]): 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, WorkstationsTransport): - # transport is a WorkstationsTransport 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_workstation_cluster(self, - request: Optional[Union[workstations.GetWorkstationClusterRequest, 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]] = (), - ) -> workstations.WorkstationCluster: - r"""Returns the requested workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_get_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation_cluster(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.GetWorkstationClusterRequest, dict]): - The request object. Request message for - GetWorkstationCluster. - name (str): - Required. Name of the requested - resource. - - 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.workstations_v1beta.types.WorkstationCluster: - A grouping of workstation - configurations and the associated - workstations in that region. - - """ - # Create or coerce a protobuf request object. - # Quick 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 workstations.GetWorkstationClusterRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.GetWorkstationClusterRequest): - request = workstations.GetWorkstationClusterRequest(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_workstation_cluster] - - # Certain 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_workstation_clusters(self, - request: Optional[Union[workstations.ListWorkstationClustersRequest, 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.ListWorkstationClustersPager: - r"""Returns all workstation clusters in the specified - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_list_workstation_clusters(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_clusters(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest, dict]): - The request object. Request message for - ListWorkstationClusters. - parent (str): - Required. Parent resource name. - 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.workstations_v1beta.services.workstations.pagers.ListWorkstationClustersPager: - Response message for - ListWorkstationClusters. - 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 workstations.ListWorkstationClustersRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.ListWorkstationClustersRequest): - request = workstations.ListWorkstationClustersRequest(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_workstation_clusters] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListWorkstationClustersPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_workstation_cluster(self, - request: Optional[Union[workstations.CreateWorkstationClusterRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation_cluster: Optional[workstations.WorkstationCluster] = None, - workstation_cluster_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_create_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationClusterRequest( - parent="parent_value", - workstation_cluster_id="workstation_cluster_id_value", - ) - - # Make the request - operation = client.create_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.CreateWorkstationClusterRequest, dict]): - The request object. Message for creating a - CreateWorkstationCluster. - parent (str): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_cluster (google.cloud.workstations_v1beta.types.WorkstationCluster): - Required. Workstation cluster to - create. - - This corresponds to the ``workstation_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_cluster_id (str): - Required. ID to use for the - workstation cluster. - - This corresponds to the ``workstation_cluster_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.workstations_v1beta.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations - in that region. - - """ - # Create or coerce a protobuf request object. - # Quick 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, workstation_cluster, workstation_cluster_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a workstations.CreateWorkstationClusterRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.CreateWorkstationClusterRequest): - request = workstations.CreateWorkstationClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation_cluster is not None: - request.workstation_cluster = workstation_cluster - if workstation_cluster_id is not None: - request.workstation_cluster_id = workstation_cluster_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_workstation_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_workstation_cluster(self, - request: Optional[Union[workstations.UpdateWorkstationClusterRequest, dict]] = None, - *, - workstation_cluster: Optional[workstations.WorkstationCluster] = 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 an existing workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_update_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationClusterRequest( - ) - - # Make the request - operation = client.update_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.UpdateWorkstationClusterRequest, dict]): - The request object. Request message for - UpdateWorkstationCluster. - workstation_cluster (google.cloud.workstations_v1beta.types.WorkstationCluster): - Required. Workstation cluster to - update. - - This corresponds to the ``workstation_cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask that specifies which - fields in the workstation cluster should - 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.workstations_v1beta.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations - in that region. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation_cluster, 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 workstations.UpdateWorkstationClusterRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.UpdateWorkstationClusterRequest): - request = workstations.UpdateWorkstationClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation_cluster is not None: - request.workstation_cluster = workstation_cluster - 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_workstation_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation_cluster.name", request.workstation_cluster.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, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_workstation_cluster(self, - request: Optional[Union[workstations.DeleteWorkstationClusterRequest, 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 the specified workstation cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_delete_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.DeleteWorkstationClusterRequest, dict]): - The request object. Message for deleting a workstation - cluster. - name (str): - Required. Name of the workstation - cluster to delete. - - 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.workstations_v1beta.types.WorkstationCluster` A grouping of workstation configurations and the associated workstations - in that region. - - """ - # Create or coerce a protobuf request object. - # Quick 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 workstations.DeleteWorkstationClusterRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.DeleteWorkstationClusterRequest): - request = workstations.DeleteWorkstationClusterRequest(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_workstation_cluster] - - # Certain 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, - workstations.WorkstationCluster, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_workstation_config(self, - request: Optional[Union[workstations.GetWorkstationConfigRequest, 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]] = (), - ) -> workstations.WorkstationConfig: - r"""Returns the requested workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_get_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.GetWorkstationConfigRequest, dict]): - The request object. Request message for - GetWorkstationConfig. - name (str): - Required. Name of the requested - resource. - - 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.workstations_v1beta.types.WorkstationConfig: - A set of configuration options - describing how a workstation will be - run. Workstation configurations are - intended to be shared across multiple - workstations. - - """ - # Create or coerce a protobuf request object. - # Quick 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 workstations.GetWorkstationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.GetWorkstationConfigRequest): - request = workstations.GetWorkstationConfigRequest(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_workstation_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_workstation_configs(self, - request: Optional[Union[workstations.ListWorkstationConfigsRequest, 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.ListWorkstationConfigsPager: - r"""Returns all workstation configurations in the - specified cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_list_workstation_configs(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest, dict]): - The request object. Request message for - ListWorkstationConfigs. - parent (str): - Required. Parent resource name. - 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.workstations_v1beta.services.workstations.pagers.ListWorkstationConfigsPager: - Response message for - ListWorkstationConfigs. - 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 workstations.ListWorkstationConfigsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.ListWorkstationConfigsRequest): - request = workstations.ListWorkstationConfigsRequest(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_workstation_configs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListWorkstationConfigsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_usable_workstation_configs(self, - request: Optional[Union[workstations.ListUsableWorkstationConfigsRequest, 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.ListUsableWorkstationConfigsPager: - r"""Returns all workstation configurations in the - specified cluster on which the caller has the - "workstations.workstation.create" permission. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_list_usable_workstation_configs(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListUsableWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstation_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest, dict]): - The request object. Request message for - ListUsableWorkstationConfigs. - parent (str): - Required. Parent resource name. - 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.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationConfigsPager: - Response message for - ListUsableWorkstationConfigs. - 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 workstations.ListUsableWorkstationConfigsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.ListUsableWorkstationConfigsRequest): - request = workstations.ListUsableWorkstationConfigsRequest(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_usable_workstation_configs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListUsableWorkstationConfigsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_workstation_config(self, - request: Optional[Union[workstations.CreateWorkstationConfigRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation_config: Optional[workstations.WorkstationConfig] = None, - workstation_config_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_create_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationConfigRequest( - parent="parent_value", - workstation_config_id="workstation_config_id_value", - ) - - # Make the request - operation = client.create_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.CreateWorkstationConfigRequest, dict]): - The request object. Message for creating a - CreateWorkstationConfig. - parent (str): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_config (google.cloud.workstations_v1beta.types.WorkstationConfig): - Required. Config to create. - This corresponds to the ``workstation_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_config_id (str): - Required. ID to use for the - workstation configuration. - - This corresponds to the ``workstation_config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.workstations_v1beta.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. - Workstation configurations are intended to be shared - across multiple workstations. - - """ - # Create or coerce a protobuf request object. - # Quick 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, workstation_config, workstation_config_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a workstations.CreateWorkstationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.CreateWorkstationConfigRequest): - request = workstations.CreateWorkstationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation_config is not None: - request.workstation_config = workstation_config - if workstation_config_id is not None: - request.workstation_config_id = workstation_config_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_workstation_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # 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, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_workstation_config(self, - request: Optional[Union[workstations.UpdateWorkstationConfigRequest, dict]] = None, - *, - workstation_config: Optional[workstations.WorkstationConfig] = 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 an existing workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_update_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationConfigRequest( - ) - - # Make the request - operation = client.update_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.UpdateWorkstationConfigRequest, dict]): - The request object. Request message for - UpdateWorkstationConfig. - workstation_config (google.cloud.workstations_v1beta.types.WorkstationConfig): - Required. Config to update. - This corresponds to the ``workstation_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask specifying which - fields in the workstation configuration - should 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.workstations_v1beta.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. - Workstation configurations are intended to be shared - across multiple workstations. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a workstations.UpdateWorkstationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.UpdateWorkstationConfigRequest): - request = workstations.UpdateWorkstationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation_config is not None: - request.workstation_config = workstation_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_workstation_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation_config.name", request.workstation_config.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, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_workstation_config(self, - request: Optional[Union[workstations.DeleteWorkstationConfigRequest, 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 the specified workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_delete_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.DeleteWorkstationConfigRequest, dict]): - The request object. Message for deleting a workstation - configuration. - name (str): - Required. Name of the workstation - configuration to delete. - - 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.workstations_v1beta.types.WorkstationConfig` A set of configuration options describing how a workstation will be run. - Workstation configurations are intended to be shared - across multiple workstations. - - """ - # Create or coerce a protobuf request object. - # Quick 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 workstations.DeleteWorkstationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.DeleteWorkstationConfigRequest): - request = workstations.DeleteWorkstationConfigRequest(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_workstation_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # 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, - workstations.WorkstationConfig, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_workstation(self, - request: Optional[Union[workstations.GetWorkstationRequest, 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]] = (), - ) -> workstations.Workstation: - r"""Returns the requested workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_get_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.GetWorkstationRequest, dict]): - The request object. Request message for GetWorkstation. - name (str): - Required. Name of the requested - resource. - - 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.workstations_v1beta.types.Workstation: - A single instance of a developer - workstation with its own persistent - storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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 workstations.GetWorkstationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.GetWorkstationRequest): - request = workstations.GetWorkstationRequest(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_workstation] - - # Certain 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_workstations(self, - request: Optional[Union[workstations.ListWorkstationsRequest, 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.ListWorkstationsPager: - r"""Returns all Workstations using the specified - workstation configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_list_workstations(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstations(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.ListWorkstationsRequest, dict]): - The request object. Request message for ListWorkstations. - parent (str): - Required. Parent resource name. - 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.workstations_v1beta.services.workstations.pagers.ListWorkstationsPager: - Response message for - ListWorkstations. - 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 workstations.ListWorkstationsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.ListWorkstationsRequest): - request = workstations.ListWorkstationsRequest(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_workstations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListWorkstationsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_usable_workstations(self, - request: Optional[Union[workstations.ListUsableWorkstationsRequest, 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.ListUsableWorkstationsPager: - r"""Returns all workstations using the specified - workstation configuration on which the caller has the - "workstations.workstations.use" permission. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_list_usable_workstations(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListUsableWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstations(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest, dict]): - The request object. Request message for - ListUsableWorkstations. - parent (str): - Required. Parent resource name. - 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.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationsPager: - Response message for - ListUsableWorkstations. - 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 workstations.ListUsableWorkstationsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.ListUsableWorkstationsRequest): - request = workstations.ListUsableWorkstationsRequest(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_usable_workstations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListUsableWorkstationsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_workstation(self, - request: Optional[Union[workstations.CreateWorkstationRequest, dict]] = None, - *, - parent: Optional[str] = None, - workstation: Optional[workstations.Workstation] = None, - workstation_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_create_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationRequest( - parent="parent_value", - workstation_id="workstation_id_value", - ) - - # Make the request - operation = client.create_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.CreateWorkstationRequest, dict]): - The request object. Message for creating a - CreateWorkstation. - parent (str): - Required. Parent resource name. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation (google.cloud.workstations_v1beta.types.Workstation): - Required. Workstation to create. - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - workstation_id (str): - Required. ID to use for the - workstation. - - This corresponds to the ``workstation_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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, workstation, workstation_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a workstations.CreateWorkstationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.CreateWorkstationRequest): - request = workstations.CreateWorkstationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if workstation is not None: - request.workstation = workstation - if workstation_id is not None: - request.workstation_id = workstation_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_workstation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_workstation(self, - request: Optional[Union[workstations.UpdateWorkstationRequest, dict]] = None, - *, - workstation: Optional[workstations.Workstation] = 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 an existing workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_update_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationRequest( - ) - - # Make the request - operation = client.update_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.UpdateWorkstationRequest, dict]): - The request object. Request message for - UpdateWorkstation. - workstation (google.cloud.workstations_v1beta.types.Workstation): - Required. Workstation to update. - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask specifying which - fields in the workstation configuration - should 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.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation, 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 workstations.UpdateWorkstationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.UpdateWorkstationRequest): - request = workstations.UpdateWorkstationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation is not None: - request.workstation = workstation - 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_workstation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation.name", request.workstation.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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_workstation(self, - request: Optional[Union[workstations.DeleteWorkstationRequest, 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 the specified workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_delete_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.DeleteWorkstationRequest, dict]): - The request object. Request message for - DeleteWorkstation. - name (str): - Required. Name of the workstation to - delete. - - 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.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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 workstations.DeleteWorkstationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.DeleteWorkstationRequest): - request = workstations.DeleteWorkstationRequest(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_workstation] - - # Certain 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def start_workstation(self, - request: Optional[Union[workstations.StartWorkstationRequest, 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"""Starts running a workstation so that users can - connect to 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 workstations_v1beta - - def sample_start_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.StartWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.start_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.StartWorkstationRequest, dict]): - The request object. Request message for StartWorkstation. - name (str): - Required. Name of the workstation to - start. - - 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.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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 workstations.StartWorkstationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.StartWorkstationRequest): - request = workstations.StartWorkstationRequest(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.start_workstation] - - # Certain 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def stop_workstation(self, - request: Optional[Union[workstations.StopWorkstationRequest, 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"""Stops running a workstation, reducing costs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_stop_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.StopWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.stop_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.StopWorkstationRequest, dict]): - The request object. Request message for StopWorkstation. - name (str): - Required. Name of the workstation to - stop. - - 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.workstations_v1beta.types.Workstation` - A single instance of a developer workstation with its - own persistent storage. - - """ - # Create or coerce a protobuf request object. - # Quick 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 workstations.StopWorkstationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.StopWorkstationRequest): - request = workstations.StopWorkstationRequest(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.stop_workstation] - - # Certain 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, - workstations.Workstation, - metadata_type=workstations.OperationMetadata, - ) - - # Done; return the response. - return response - - def generate_access_token(self, - request: Optional[Union[workstations.GenerateAccessTokenRequest, dict]] = None, - *, - workstation: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> workstations.GenerateAccessTokenResponse: - r"""Returns a short-lived credential that can be used to - send authenticated and authorized traffic to a - workstation. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import workstations_v1beta - - def sample_generate_access_token(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.GenerateAccessTokenRequest( - workstation="workstation_value", - ) - - # Make the request - response = client.generate_access_token(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.workstations_v1beta.types.GenerateAccessTokenRequest, dict]): - The request object. Request message for - GenerateAccessToken. - workstation (str): - Required. Name of the workstation for - which the access token should be - generated. - - This corresponds to the ``workstation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.workstations_v1beta.types.GenerateAccessTokenResponse: - Response message for - GenerateAccessToken. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([workstation]) - if request is 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 workstations.GenerateAccessTokenRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, workstations.GenerateAccessTokenRequest): - request = workstations.GenerateAccessTokenRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if workstation is not None: - request.workstation = workstation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_access_token] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("workstation", request.workstation), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "WorkstationsClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "WorkstationsClient", -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/pagers.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/pagers.py deleted file mode 100644 index af615b450476..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/pagers.py +++ /dev/null @@ -1,623 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.workstations_v1beta.types import workstations - - -class ListWorkstationClustersPager: - """A pager for iterating through ``list_workstation_clusters`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstation_clusters`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListWorkstationClusters`` requests and continue to iterate - through the ``workstation_clusters`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse` - 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[..., workstations.ListWorkstationClustersResponse], - request: workstations.ListWorkstationClustersRequest, - response: workstations.ListWorkstationClustersResponse, - *, - 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.workstations_v1beta.types.ListWorkstationClustersRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse): - 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 = workstations.ListWorkstationClustersRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[workstations.ListWorkstationClustersResponse]: - 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[workstations.WorkstationCluster]: - for page in self.pages: - yield from page.workstation_clusters - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationClustersAsyncPager: - """A pager for iterating through ``list_workstation_clusters`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstation_clusters`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListWorkstationClusters`` requests and continue to iterate - through the ``workstation_clusters`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse` - 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[workstations.ListWorkstationClustersResponse]], - request: workstations.ListWorkstationClustersRequest, - response: workstations.ListWorkstationClustersResponse, - *, - 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.workstations_v1beta.types.ListWorkstationClustersRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListWorkstationClustersResponse): - 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 = workstations.ListWorkstationClustersRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[workstations.ListWorkstationClustersResponse]: - 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[workstations.WorkstationCluster]: - async def async_generator(): - async for page in self.pages: - for response in page.workstation_clusters: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationConfigsPager: - """A pager for iterating through ``list_workstation_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstation_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListWorkstationConfigs`` requests and continue to iterate - through the ``workstation_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse` - 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[..., workstations.ListWorkstationConfigsResponse], - request: workstations.ListWorkstationConfigsRequest, - response: workstations.ListWorkstationConfigsResponse, - *, - 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.workstations_v1beta.types.ListWorkstationConfigsRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse): - 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 = workstations.ListWorkstationConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[workstations.ListWorkstationConfigsResponse]: - 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[workstations.WorkstationConfig]: - for page in self.pages: - yield from page.workstation_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationConfigsAsyncPager: - """A pager for iterating through ``list_workstation_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstation_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListWorkstationConfigs`` requests and continue to iterate - through the ``workstation_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse` - 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[workstations.ListWorkstationConfigsResponse]], - request: workstations.ListWorkstationConfigsRequest, - response: workstations.ListWorkstationConfigsResponse, - *, - 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.workstations_v1beta.types.ListWorkstationConfigsRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListWorkstationConfigsResponse): - 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 = workstations.ListWorkstationConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[workstations.ListWorkstationConfigsResponse]: - 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[workstations.WorkstationConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.workstation_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUsableWorkstationConfigsPager: - """A pager for iterating through ``list_usable_workstation_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstation_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListUsableWorkstationConfigs`` requests and continue to iterate - through the ``workstation_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse` - 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[..., workstations.ListUsableWorkstationConfigsResponse], - request: workstations.ListUsableWorkstationConfigsRequest, - response: workstations.ListUsableWorkstationConfigsResponse, - *, - 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.workstations_v1beta.types.ListUsableWorkstationConfigsRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse): - 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 = workstations.ListUsableWorkstationConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[workstations.ListUsableWorkstationConfigsResponse]: - 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[workstations.WorkstationConfig]: - for page in self.pages: - yield from page.workstation_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUsableWorkstationConfigsAsyncPager: - """A pager for iterating through ``list_usable_workstation_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstation_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListUsableWorkstationConfigs`` requests and continue to iterate - through the ``workstation_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse` - 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[workstations.ListUsableWorkstationConfigsResponse]], - request: workstations.ListUsableWorkstationConfigsRequest, - response: workstations.ListUsableWorkstationConfigsResponse, - *, - 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.workstations_v1beta.types.ListUsableWorkstationConfigsRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsResponse): - 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 = workstations.ListUsableWorkstationConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[workstations.ListUsableWorkstationConfigsResponse]: - 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[workstations.WorkstationConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.workstation_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationsPager: - """A pager for iterating through ``list_workstations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListWorkstationsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstations`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListWorkstations`` requests and continue to iterate - through the ``workstations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationsResponse` - 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[..., workstations.ListWorkstationsResponse], - request: workstations.ListWorkstationsRequest, - response: workstations.ListWorkstationsResponse, - *, - 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.workstations_v1beta.types.ListWorkstationsRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListWorkstationsResponse): - 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 = workstations.ListWorkstationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[workstations.ListWorkstationsResponse]: - 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[workstations.Workstation]: - for page in self.pages: - yield from page.workstations - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkstationsAsyncPager: - """A pager for iterating through ``list_workstations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListWorkstationsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstations`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListWorkstations`` requests and continue to iterate - through the ``workstations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListWorkstationsResponse` - 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[workstations.ListWorkstationsResponse]], - request: workstations.ListWorkstationsRequest, - response: workstations.ListWorkstationsResponse, - *, - 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.workstations_v1beta.types.ListWorkstationsRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListWorkstationsResponse): - 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 = workstations.ListWorkstationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[workstations.ListWorkstationsResponse]: - 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[workstations.Workstation]: - async def async_generator(): - async for page in self.pages: - for response in page.workstations: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUsableWorkstationsPager: - """A pager for iterating through ``list_usable_workstations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workstations`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListUsableWorkstations`` requests and continue to iterate - through the ``workstations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse` - 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[..., workstations.ListUsableWorkstationsResponse], - request: workstations.ListUsableWorkstationsRequest, - response: workstations.ListUsableWorkstationsResponse, - *, - 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.workstations_v1beta.types.ListUsableWorkstationsRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse): - 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 = workstations.ListUsableWorkstationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[workstations.ListUsableWorkstationsResponse]: - 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[workstations.Workstation]: - for page in self.pages: - yield from page.workstations - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUsableWorkstationsAsyncPager: - """A pager for iterating through ``list_usable_workstations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workstations`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListUsableWorkstations`` requests and continue to iterate - through the ``workstations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse` - 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[workstations.ListUsableWorkstationsResponse]], - request: workstations.ListUsableWorkstationsRequest, - response: workstations.ListUsableWorkstationsResponse, - *, - 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.workstations_v1beta.types.ListUsableWorkstationsRequest): - The initial request object. - response (google.cloud.workstations_v1beta.types.ListUsableWorkstationsResponse): - 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 = workstations.ListUsableWorkstationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[workstations.ListUsableWorkstationsResponse]: - 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[workstations.Workstation]: - async def async_generator(): - async for page in self.pages: - for response in page.workstations: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/__init__.py deleted file mode 100644 index fc931d51cd5e..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 WorkstationsTransport -from .grpc import WorkstationsGrpcTransport -from .grpc_asyncio import WorkstationsGrpcAsyncIOTransport -from .rest import WorkstationsRestTransport -from .rest import WorkstationsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[WorkstationsTransport]] -_transport_registry['grpc'] = WorkstationsGrpcTransport -_transport_registry['grpc_asyncio'] = WorkstationsGrpcAsyncIOTransport -_transport_registry['rest'] = WorkstationsRestTransport - -__all__ = ( - 'WorkstationsTransport', - 'WorkstationsGrpcTransport', - 'WorkstationsGrpcAsyncIOTransport', - 'WorkstationsRestTransport', - 'WorkstationsRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/base.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/base.py deleted file mode 100644 index 9acf0ecb73c3..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/base.py +++ /dev/null @@ -1,545 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.workstations_v1beta 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.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1beta.types import workstations -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 -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class WorkstationsTransport(abc.ABC): - """Abstract transport class for Workstations.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'workstations.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_workstation_cluster: gapic_v1.method.wrap_method( - self.get_workstation_cluster, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_workstation_clusters: gapic_v1.method.wrap_method( - self.list_workstation_clusters, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_workstation_cluster: gapic_v1.method.wrap_method( - self.create_workstation_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.update_workstation_cluster: gapic_v1.method.wrap_method( - self.update_workstation_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_workstation_cluster: gapic_v1.method.wrap_method( - self.delete_workstation_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.get_workstation_config: gapic_v1.method.wrap_method( - self.get_workstation_config, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_workstation_configs: gapic_v1.method.wrap_method( - self.list_workstation_configs, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_usable_workstation_configs: gapic_v1.method.wrap_method( - self.list_usable_workstation_configs, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_workstation_config: gapic_v1.method.wrap_method( - self.create_workstation_config, - default_timeout=60.0, - client_info=client_info, - ), - self.update_workstation_config: gapic_v1.method.wrap_method( - self.update_workstation_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_workstation_config: gapic_v1.method.wrap_method( - self.delete_workstation_config, - default_timeout=60.0, - client_info=client_info, - ), - self.get_workstation: gapic_v1.method.wrap_method( - self.get_workstation, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_workstations: gapic_v1.method.wrap_method( - self.list_workstations, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_usable_workstations: gapic_v1.method.wrap_method( - self.list_usable_workstations, - default_retry=retries.Retry( -initial=1.0,maximum=10.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_workstation: gapic_v1.method.wrap_method( - self.create_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.update_workstation: gapic_v1.method.wrap_method( - self.update_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_workstation: gapic_v1.method.wrap_method( - self.delete_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.start_workstation: gapic_v1.method.wrap_method( - self.start_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.stop_workstation: gapic_v1.method.wrap_method( - self.stop_workstation, - default_timeout=60.0, - client_info=client_info, - ), - self.generate_access_token: gapic_v1.method.wrap_method( - self.generate_access_token, - default_retry=retries.Retry( -initial=1.0,maximum=10.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - 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 get_workstation_cluster(self) -> Callable[ - [workstations.GetWorkstationClusterRequest], - Union[ - workstations.WorkstationCluster, - Awaitable[workstations.WorkstationCluster] - ]]: - raise NotImplementedError() - - @property - def list_workstation_clusters(self) -> Callable[ - [workstations.ListWorkstationClustersRequest], - Union[ - workstations.ListWorkstationClustersResponse, - Awaitable[workstations.ListWorkstationClustersResponse] - ]]: - raise NotImplementedError() - - @property - def create_workstation_cluster(self) -> Callable[ - [workstations.CreateWorkstationClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_workstation_cluster(self) -> Callable[ - [workstations.UpdateWorkstationClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_workstation_cluster(self) -> Callable[ - [workstations.DeleteWorkstationClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_workstation_config(self) -> Callable[ - [workstations.GetWorkstationConfigRequest], - Union[ - workstations.WorkstationConfig, - Awaitable[workstations.WorkstationConfig] - ]]: - raise NotImplementedError() - - @property - def list_workstation_configs(self) -> Callable[ - [workstations.ListWorkstationConfigsRequest], - Union[ - workstations.ListWorkstationConfigsResponse, - Awaitable[workstations.ListWorkstationConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def list_usable_workstation_configs(self) -> Callable[ - [workstations.ListUsableWorkstationConfigsRequest], - Union[ - workstations.ListUsableWorkstationConfigsResponse, - Awaitable[workstations.ListUsableWorkstationConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def create_workstation_config(self) -> Callable[ - [workstations.CreateWorkstationConfigRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_workstation_config(self) -> Callable[ - [workstations.UpdateWorkstationConfigRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_workstation_config(self) -> Callable[ - [workstations.DeleteWorkstationConfigRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_workstation(self) -> Callable[ - [workstations.GetWorkstationRequest], - Union[ - workstations.Workstation, - Awaitable[workstations.Workstation] - ]]: - raise NotImplementedError() - - @property - def list_workstations(self) -> Callable[ - [workstations.ListWorkstationsRequest], - Union[ - workstations.ListWorkstationsResponse, - Awaitable[workstations.ListWorkstationsResponse] - ]]: - raise NotImplementedError() - - @property - def list_usable_workstations(self) -> Callable[ - [workstations.ListUsableWorkstationsRequest], - Union[ - workstations.ListUsableWorkstationsResponse, - Awaitable[workstations.ListUsableWorkstationsResponse] - ]]: - raise NotImplementedError() - - @property - def create_workstation(self) -> Callable[ - [workstations.CreateWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_workstation(self) -> Callable[ - [workstations.UpdateWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_workstation(self) -> Callable[ - [workstations.DeleteWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def start_workstation(self) -> Callable[ - [workstations.StartWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def stop_workstation(self) -> Callable[ - [workstations.StopWorkstationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def generate_access_token(self) -> Callable[ - [workstations.GenerateAccessTokenRequest], - Union[ - workstations.GenerateAccessTokenResponse, - Awaitable[workstations.GenerateAccessTokenResponse] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def delete_operation( - self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def set_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse], - ], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'WorkstationsTransport', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc.py deleted file mode 100644 index 0d74bc29c385..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc.py +++ /dev/null @@ -1,943 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1beta.types import workstations -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 -from google.longrunning import operations_pb2 # type: ignore -from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO - - -class WorkstationsGrpcTransport(WorkstationsTransport): - """gRPC backend transport for Workstations. - - Service for interacting with Cloud Workstations. - - 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 = 'workstations.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 = 'workstations.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_workstation_cluster(self) -> Callable[ - [workstations.GetWorkstationClusterRequest], - workstations.WorkstationCluster]: - r"""Return a callable for the get workstation cluster method over gRPC. - - Returns the requested workstation cluster. - - Returns: - Callable[[~.GetWorkstationClusterRequest], - ~.WorkstationCluster]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: - self._stubs['get_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/GetWorkstationCluster', - request_serializer=workstations.GetWorkstationClusterRequest.serialize, - response_deserializer=workstations.WorkstationCluster.deserialize, - ) - return self._stubs['get_workstation_cluster'] - - @property - def list_workstation_clusters(self) -> Callable[ - [workstations.ListWorkstationClustersRequest], - workstations.ListWorkstationClustersResponse]: - r"""Return a callable for the list workstation clusters method over gRPC. - - Returns all workstation clusters in the specified - location. - - Returns: - Callable[[~.ListWorkstationClustersRequest], - ~.ListWorkstationClustersResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_clusters' not in self._stubs: - self._stubs['list_workstation_clusters'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListWorkstationClusters', - request_serializer=workstations.ListWorkstationClustersRequest.serialize, - response_deserializer=workstations.ListWorkstationClustersResponse.deserialize, - ) - return self._stubs['list_workstation_clusters'] - - @property - def create_workstation_cluster(self) -> Callable[ - [workstations.CreateWorkstationClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the create workstation cluster method over gRPC. - - Creates a new workstation cluster. - - Returns: - Callable[[~.CreateWorkstationClusterRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: - self._stubs['create_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/CreateWorkstationCluster', - request_serializer=workstations.CreateWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation_cluster'] - - @property - def update_workstation_cluster(self) -> Callable[ - [workstations.UpdateWorkstationClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the update workstation cluster method over gRPC. - - Updates an existing workstation cluster. - - Returns: - Callable[[~.UpdateWorkstationClusterRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: - self._stubs['update_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstationCluster', - request_serializer=workstations.UpdateWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation_cluster'] - - @property - def delete_workstation_cluster(self) -> Callable[ - [workstations.DeleteWorkstationClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete workstation cluster method over gRPC. - - Deletes the specified workstation cluster. - - Returns: - Callable[[~.DeleteWorkstationClusterRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: - self._stubs['delete_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstationCluster', - request_serializer=workstations.DeleteWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation_cluster'] - - @property - def get_workstation_config(self) -> Callable[ - [workstations.GetWorkstationConfigRequest], - workstations.WorkstationConfig]: - r"""Return a callable for the get workstation config method over gRPC. - - Returns the requested workstation configuration. - - Returns: - Callable[[~.GetWorkstationConfigRequest], - ~.WorkstationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: - self._stubs['get_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/GetWorkstationConfig', - request_serializer=workstations.GetWorkstationConfigRequest.serialize, - response_deserializer=workstations.WorkstationConfig.deserialize, - ) - return self._stubs['get_workstation_config'] - - @property - def list_workstation_configs(self) -> Callable[ - [workstations.ListWorkstationConfigsRequest], - workstations.ListWorkstationConfigsResponse]: - r"""Return a callable for the list workstation configs method over gRPC. - - Returns all workstation configurations in the - specified cluster. - - Returns: - Callable[[~.ListWorkstationConfigsRequest], - ~.ListWorkstationConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_configs' not in self._stubs: - self._stubs['list_workstation_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListWorkstationConfigs', - request_serializer=workstations.ListWorkstationConfigsRequest.serialize, - response_deserializer=workstations.ListWorkstationConfigsResponse.deserialize, - ) - return self._stubs['list_workstation_configs'] - - @property - def list_usable_workstation_configs(self) -> Callable[ - [workstations.ListUsableWorkstationConfigsRequest], - workstations.ListUsableWorkstationConfigsResponse]: - r"""Return a callable for the list usable workstation - configs method over gRPC. - - Returns all workstation configurations in the - specified cluster on which the caller has the - "workstations.workstation.create" permission. - - Returns: - Callable[[~.ListUsableWorkstationConfigsRequest], - ~.ListUsableWorkstationConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_usable_workstation_configs' not in self._stubs: - self._stubs['list_usable_workstation_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListUsableWorkstationConfigs', - request_serializer=workstations.ListUsableWorkstationConfigsRequest.serialize, - response_deserializer=workstations.ListUsableWorkstationConfigsResponse.deserialize, - ) - return self._stubs['list_usable_workstation_configs'] - - @property - def create_workstation_config(self) -> Callable[ - [workstations.CreateWorkstationConfigRequest], - operations_pb2.Operation]: - r"""Return a callable for the create workstation config method over gRPC. - - Creates a new workstation configuration. - - Returns: - Callable[[~.CreateWorkstationConfigRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: - self._stubs['create_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/CreateWorkstationConfig', - request_serializer=workstations.CreateWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation_config'] - - @property - def update_workstation_config(self) -> Callable[ - [workstations.UpdateWorkstationConfigRequest], - operations_pb2.Operation]: - r"""Return a callable for the update workstation config method over gRPC. - - Updates an existing workstation configuration. - - Returns: - Callable[[~.UpdateWorkstationConfigRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: - self._stubs['update_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstationConfig', - request_serializer=workstations.UpdateWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation_config'] - - @property - def delete_workstation_config(self) -> Callable[ - [workstations.DeleteWorkstationConfigRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete workstation config method over gRPC. - - Deletes the specified workstation configuration. - - Returns: - Callable[[~.DeleteWorkstationConfigRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: - self._stubs['delete_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstationConfig', - request_serializer=workstations.DeleteWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation_config'] - - @property - def get_workstation(self) -> Callable[ - [workstations.GetWorkstationRequest], - workstations.Workstation]: - r"""Return a callable for the get workstation method over gRPC. - - Returns the requested workstation. - - Returns: - Callable[[~.GetWorkstationRequest], - ~.Workstation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation' not in self._stubs: - self._stubs['get_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/GetWorkstation', - request_serializer=workstations.GetWorkstationRequest.serialize, - response_deserializer=workstations.Workstation.deserialize, - ) - return self._stubs['get_workstation'] - - @property - def list_workstations(self) -> Callable[ - [workstations.ListWorkstationsRequest], - workstations.ListWorkstationsResponse]: - r"""Return a callable for the list workstations method over gRPC. - - Returns all Workstations using the specified - workstation configuration. - - Returns: - Callable[[~.ListWorkstationsRequest], - ~.ListWorkstationsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstations' not in self._stubs: - self._stubs['list_workstations'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListWorkstations', - request_serializer=workstations.ListWorkstationsRequest.serialize, - response_deserializer=workstations.ListWorkstationsResponse.deserialize, - ) - return self._stubs['list_workstations'] - - @property - def list_usable_workstations(self) -> Callable[ - [workstations.ListUsableWorkstationsRequest], - workstations.ListUsableWorkstationsResponse]: - r"""Return a callable for the list usable workstations method over gRPC. - - Returns all workstations using the specified - workstation configuration on which the caller has the - "workstations.workstations.use" permission. - - Returns: - Callable[[~.ListUsableWorkstationsRequest], - ~.ListUsableWorkstationsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_usable_workstations' not in self._stubs: - self._stubs['list_usable_workstations'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListUsableWorkstations', - request_serializer=workstations.ListUsableWorkstationsRequest.serialize, - response_deserializer=workstations.ListUsableWorkstationsResponse.deserialize, - ) - return self._stubs['list_usable_workstations'] - - @property - def create_workstation(self) -> Callable[ - [workstations.CreateWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the create workstation method over gRPC. - - Creates a new workstation. - - Returns: - Callable[[~.CreateWorkstationRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation' not in self._stubs: - self._stubs['create_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/CreateWorkstation', - request_serializer=workstations.CreateWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation'] - - @property - def update_workstation(self) -> Callable[ - [workstations.UpdateWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the update workstation method over gRPC. - - Updates an existing workstation. - - Returns: - Callable[[~.UpdateWorkstationRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation' not in self._stubs: - self._stubs['update_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstation', - request_serializer=workstations.UpdateWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation'] - - @property - def delete_workstation(self) -> Callable[ - [workstations.DeleteWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete workstation method over gRPC. - - Deletes the specified workstation. - - Returns: - Callable[[~.DeleteWorkstationRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation' not in self._stubs: - self._stubs['delete_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstation', - request_serializer=workstations.DeleteWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation'] - - @property - def start_workstation(self) -> Callable[ - [workstations.StartWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the start workstation method over gRPC. - - Starts running a workstation so that users can - connect to it. - - Returns: - Callable[[~.StartWorkstationRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_workstation' not in self._stubs: - self._stubs['start_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/StartWorkstation', - request_serializer=workstations.StartWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['start_workstation'] - - @property - def stop_workstation(self) -> Callable[ - [workstations.StopWorkstationRequest], - operations_pb2.Operation]: - r"""Return a callable for the stop workstation method over gRPC. - - Stops running a workstation, reducing costs. - - Returns: - Callable[[~.StopWorkstationRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_workstation' not in self._stubs: - self._stubs['stop_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/StopWorkstation', - request_serializer=workstations.StopWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['stop_workstation'] - - @property - def generate_access_token(self) -> Callable[ - [workstations.GenerateAccessTokenRequest], - workstations.GenerateAccessTokenResponse]: - r"""Return a callable for the generate access token method over gRPC. - - Returns a short-lived credential that can be used to - send authenticated and authorized traffic to a - workstation. - - Returns: - Callable[[~.GenerateAccessTokenRequest], - ~.GenerateAccessTokenResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_access_token' not in self._stubs: - self._stubs['generate_access_token'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/GenerateAccessToken', - request_serializer=workstations.GenerateAccessTokenRequest.serialize, - response_deserializer=workstations.GenerateAccessTokenResponse.deserialize, - ) - return self._stubs['generate_access_token'] - - def close(self): - self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'WorkstationsGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc_asyncio.py deleted file mode 100644 index 14724fe951e7..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/grpc_asyncio.py +++ /dev/null @@ -1,942 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.location import locations_pb2 # type: ignore -from google.cloud.workstations_v1beta.types import workstations -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 -from google.longrunning import operations_pb2 # type: ignore -from .base import WorkstationsTransport, DEFAULT_CLIENT_INFO -from .grpc import WorkstationsGrpcTransport - - -class WorkstationsGrpcAsyncIOTransport(WorkstationsTransport): - """gRPC AsyncIO backend transport for Workstations. - - Service for interacting with Cloud Workstations. - - 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 = 'workstations.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 = 'workstations.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_workstation_cluster(self) -> Callable[ - [workstations.GetWorkstationClusterRequest], - Awaitable[workstations.WorkstationCluster]]: - r"""Return a callable for the get workstation cluster method over gRPC. - - Returns the requested workstation cluster. - - Returns: - Callable[[~.GetWorkstationClusterRequest], - Awaitable[~.WorkstationCluster]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_cluster' not in self._stubs: - self._stubs['get_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/GetWorkstationCluster', - request_serializer=workstations.GetWorkstationClusterRequest.serialize, - response_deserializer=workstations.WorkstationCluster.deserialize, - ) - return self._stubs['get_workstation_cluster'] - - @property - def list_workstation_clusters(self) -> Callable[ - [workstations.ListWorkstationClustersRequest], - Awaitable[workstations.ListWorkstationClustersResponse]]: - r"""Return a callable for the list workstation clusters method over gRPC. - - Returns all workstation clusters in the specified - location. - - Returns: - Callable[[~.ListWorkstationClustersRequest], - Awaitable[~.ListWorkstationClustersResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_clusters' not in self._stubs: - self._stubs['list_workstation_clusters'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListWorkstationClusters', - request_serializer=workstations.ListWorkstationClustersRequest.serialize, - response_deserializer=workstations.ListWorkstationClustersResponse.deserialize, - ) - return self._stubs['list_workstation_clusters'] - - @property - def create_workstation_cluster(self) -> Callable[ - [workstations.CreateWorkstationClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create workstation cluster method over gRPC. - - Creates a new workstation cluster. - - Returns: - Callable[[~.CreateWorkstationClusterRequest], - 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_workstation_cluster' not in self._stubs: - self._stubs['create_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/CreateWorkstationCluster', - request_serializer=workstations.CreateWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation_cluster'] - - @property - def update_workstation_cluster(self) -> Callable[ - [workstations.UpdateWorkstationClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update workstation cluster method over gRPC. - - Updates an existing workstation cluster. - - Returns: - Callable[[~.UpdateWorkstationClusterRequest], - 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_workstation_cluster' not in self._stubs: - self._stubs['update_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstationCluster', - request_serializer=workstations.UpdateWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation_cluster'] - - @property - def delete_workstation_cluster(self) -> Callable[ - [workstations.DeleteWorkstationClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete workstation cluster method over gRPC. - - Deletes the specified workstation cluster. - - Returns: - Callable[[~.DeleteWorkstationClusterRequest], - 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_workstation_cluster' not in self._stubs: - self._stubs['delete_workstation_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstationCluster', - request_serializer=workstations.DeleteWorkstationClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation_cluster'] - - @property - def get_workstation_config(self) -> Callable[ - [workstations.GetWorkstationConfigRequest], - Awaitable[workstations.WorkstationConfig]]: - r"""Return a callable for the get workstation config method over gRPC. - - Returns the requested workstation configuration. - - Returns: - Callable[[~.GetWorkstationConfigRequest], - Awaitable[~.WorkstationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_config' not in self._stubs: - self._stubs['get_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/GetWorkstationConfig', - request_serializer=workstations.GetWorkstationConfigRequest.serialize, - response_deserializer=workstations.WorkstationConfig.deserialize, - ) - return self._stubs['get_workstation_config'] - - @property - def list_workstation_configs(self) -> Callable[ - [workstations.ListWorkstationConfigsRequest], - Awaitable[workstations.ListWorkstationConfigsResponse]]: - r"""Return a callable for the list workstation configs method over gRPC. - - Returns all workstation configurations in the - specified cluster. - - Returns: - Callable[[~.ListWorkstationConfigsRequest], - Awaitable[~.ListWorkstationConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation_configs' not in self._stubs: - self._stubs['list_workstation_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListWorkstationConfigs', - request_serializer=workstations.ListWorkstationConfigsRequest.serialize, - response_deserializer=workstations.ListWorkstationConfigsResponse.deserialize, - ) - return self._stubs['list_workstation_configs'] - - @property - def list_usable_workstation_configs(self) -> Callable[ - [workstations.ListUsableWorkstationConfigsRequest], - Awaitable[workstations.ListUsableWorkstationConfigsResponse]]: - r"""Return a callable for the list usable workstation - configs method over gRPC. - - Returns all workstation configurations in the - specified cluster on which the caller has the - "workstations.workstation.create" permission. - - Returns: - Callable[[~.ListUsableWorkstationConfigsRequest], - Awaitable[~.ListUsableWorkstationConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_usable_workstation_configs' not in self._stubs: - self._stubs['list_usable_workstation_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListUsableWorkstationConfigs', - request_serializer=workstations.ListUsableWorkstationConfigsRequest.serialize, - response_deserializer=workstations.ListUsableWorkstationConfigsResponse.deserialize, - ) - return self._stubs['list_usable_workstation_configs'] - - @property - def create_workstation_config(self) -> Callable[ - [workstations.CreateWorkstationConfigRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create workstation config method over gRPC. - - Creates a new workstation configuration. - - Returns: - Callable[[~.CreateWorkstationConfigRequest], - 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_workstation_config' not in self._stubs: - self._stubs['create_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/CreateWorkstationConfig', - request_serializer=workstations.CreateWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation_config'] - - @property - def update_workstation_config(self) -> Callable[ - [workstations.UpdateWorkstationConfigRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update workstation config method over gRPC. - - Updates an existing workstation configuration. - - Returns: - Callable[[~.UpdateWorkstationConfigRequest], - 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_workstation_config' not in self._stubs: - self._stubs['update_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstationConfig', - request_serializer=workstations.UpdateWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation_config'] - - @property - def delete_workstation_config(self) -> Callable[ - [workstations.DeleteWorkstationConfigRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete workstation config method over gRPC. - - Deletes the specified workstation configuration. - - Returns: - Callable[[~.DeleteWorkstationConfigRequest], - 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_workstation_config' not in self._stubs: - self._stubs['delete_workstation_config'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstationConfig', - request_serializer=workstations.DeleteWorkstationConfigRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation_config'] - - @property - def get_workstation(self) -> Callable[ - [workstations.GetWorkstationRequest], - Awaitable[workstations.Workstation]]: - r"""Return a callable for the get workstation method over gRPC. - - Returns the requested workstation. - - Returns: - Callable[[~.GetWorkstationRequest], - Awaitable[~.Workstation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstation' not in self._stubs: - self._stubs['get_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/GetWorkstation', - request_serializer=workstations.GetWorkstationRequest.serialize, - response_deserializer=workstations.Workstation.deserialize, - ) - return self._stubs['get_workstation'] - - @property - def list_workstations(self) -> Callable[ - [workstations.ListWorkstationsRequest], - Awaitable[workstations.ListWorkstationsResponse]]: - r"""Return a callable for the list workstations method over gRPC. - - Returns all Workstations using the specified - workstation configuration. - - Returns: - Callable[[~.ListWorkstationsRequest], - Awaitable[~.ListWorkstationsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workstations' not in self._stubs: - self._stubs['list_workstations'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListWorkstations', - request_serializer=workstations.ListWorkstationsRequest.serialize, - response_deserializer=workstations.ListWorkstationsResponse.deserialize, - ) - return self._stubs['list_workstations'] - - @property - def list_usable_workstations(self) -> Callable[ - [workstations.ListUsableWorkstationsRequest], - Awaitable[workstations.ListUsableWorkstationsResponse]]: - r"""Return a callable for the list usable workstations method over gRPC. - - Returns all workstations using the specified - workstation configuration on which the caller has the - "workstations.workstations.use" permission. - - Returns: - Callable[[~.ListUsableWorkstationsRequest], - Awaitable[~.ListUsableWorkstationsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_usable_workstations' not in self._stubs: - self._stubs['list_usable_workstations'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/ListUsableWorkstations', - request_serializer=workstations.ListUsableWorkstationsRequest.serialize, - response_deserializer=workstations.ListUsableWorkstationsResponse.deserialize, - ) - return self._stubs['list_usable_workstations'] - - @property - def create_workstation(self) -> Callable[ - [workstations.CreateWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create workstation method over gRPC. - - Creates a new workstation. - - Returns: - Callable[[~.CreateWorkstationRequest], - 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_workstation' not in self._stubs: - self._stubs['create_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/CreateWorkstation', - request_serializer=workstations.CreateWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_workstation'] - - @property - def update_workstation(self) -> Callable[ - [workstations.UpdateWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update workstation method over gRPC. - - Updates an existing workstation. - - Returns: - Callable[[~.UpdateWorkstationRequest], - 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_workstation' not in self._stubs: - self._stubs['update_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/UpdateWorkstation', - request_serializer=workstations.UpdateWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_workstation'] - - @property - def delete_workstation(self) -> Callable[ - [workstations.DeleteWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete workstation method over gRPC. - - Deletes the specified workstation. - - Returns: - Callable[[~.DeleteWorkstationRequest], - 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_workstation' not in self._stubs: - self._stubs['delete_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/DeleteWorkstation', - request_serializer=workstations.DeleteWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_workstation'] - - @property - def start_workstation(self) -> Callable[ - [workstations.StartWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the start workstation method over gRPC. - - Starts running a workstation so that users can - connect to it. - - Returns: - Callable[[~.StartWorkstationRequest], - 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 'start_workstation' not in self._stubs: - self._stubs['start_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/StartWorkstation', - request_serializer=workstations.StartWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['start_workstation'] - - @property - def stop_workstation(self) -> Callable[ - [workstations.StopWorkstationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the stop workstation method over gRPC. - - Stops running a workstation, reducing costs. - - Returns: - Callable[[~.StopWorkstationRequest], - 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 'stop_workstation' not in self._stubs: - self._stubs['stop_workstation'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/StopWorkstation', - request_serializer=workstations.StopWorkstationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['stop_workstation'] - - @property - def generate_access_token(self) -> Callable[ - [workstations.GenerateAccessTokenRequest], - Awaitable[workstations.GenerateAccessTokenResponse]]: - r"""Return a callable for the generate access token method over gRPC. - - Returns a short-lived credential that can be used to - send authenticated and authorized traffic to a - workstation. - - Returns: - Callable[[~.GenerateAccessTokenRequest], - Awaitable[~.GenerateAccessTokenResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_access_token' not in self._stubs: - self._stubs['generate_access_token'] = self.grpc_channel.unary_unary( - '/google.cloud.workstations.v1beta.Workstations/GenerateAccessToken', - request_serializer=workstations.GenerateAccessTokenRequest.serialize, - response_deserializer=workstations.GenerateAccessTokenResponse.deserialize, - ) - return self._stubs['generate_access_token'] - - def close(self): - return self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'WorkstationsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest.py deleted file mode 100644 index 3d49638dac6d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/services/workstations/transports/rest.py +++ /dev/null @@ -1,3177 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.workstations_v1beta.types import workstations -from google.longrunning import operations_pb2 # type: ignore - -from .base import WorkstationsTransport, 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 WorkstationsRestInterceptor: - """Interceptor for Workstations. - - 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 WorkstationsRestTransport. - - .. code-block:: python - class MyCustomWorkstationsInterceptor(WorkstationsRestInterceptor): - def pre_create_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_workstation_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_workstation_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_workstation_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_workstation_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_workstation_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_workstation_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_workstation_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_workstation_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_generate_access_token(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_generate_access_token(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_workstation_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_workstation_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_workstation_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_workstation_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_usable_workstation_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_usable_workstation_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_usable_workstations(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_usable_workstations(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_workstation_clusters(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_workstation_clusters(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_workstation_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_workstation_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_workstations(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_workstations(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_start_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_start_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_stop_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_stop_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_workstation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_workstation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_workstation_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_workstation_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_workstation_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_workstation_config(self, response): - logging.log(f"Received response: {response}") - return response - - transport = WorkstationsRestTransport(interceptor=MyCustomWorkstationsInterceptor()) - client = WorkstationsClient(transport=transport) - - - """ - def pre_create_workstation(self, request: workstations.CreateWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_create_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_create_workstation_cluster(self, request: workstations.CreateWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_workstation_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_create_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_workstation_cluster - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_create_workstation_config(self, request: workstations.CreateWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.CreateWorkstationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_workstation_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_create_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_workstation_config - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_delete_workstation(self, request: workstations.DeleteWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_delete_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_delete_workstation_cluster(self, request: workstations.DeleteWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_workstation_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_delete_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_workstation_cluster - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_delete_workstation_config(self, request: workstations.DeleteWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.DeleteWorkstationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_workstation_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_delete_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_workstation_config - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_generate_access_token(self, request: workstations.GenerateAccessTokenRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GenerateAccessTokenRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for generate_access_token - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_generate_access_token(self, response: workstations.GenerateAccessTokenResponse) -> workstations.GenerateAccessTokenResponse: - """Post-rpc interceptor for generate_access_token - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_get_workstation(self, request: workstations.GetWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_get_workstation(self, response: workstations.Workstation) -> workstations.Workstation: - """Post-rpc interceptor for get_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_get_workstation_cluster(self, request: workstations.GetWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_workstation_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_get_workstation_cluster(self, response: workstations.WorkstationCluster) -> workstations.WorkstationCluster: - """Post-rpc interceptor for get_workstation_cluster - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_get_workstation_config(self, request: workstations.GetWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.GetWorkstationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_workstation_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_get_workstation_config(self, response: workstations.WorkstationConfig) -> workstations.WorkstationConfig: - """Post-rpc interceptor for get_workstation_config - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_list_usable_workstation_configs(self, request: workstations.ListUsableWorkstationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListUsableWorkstationConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_usable_workstation_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_usable_workstation_configs(self, response: workstations.ListUsableWorkstationConfigsResponse) -> workstations.ListUsableWorkstationConfigsResponse: - """Post-rpc interceptor for list_usable_workstation_configs - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_list_usable_workstations(self, request: workstations.ListUsableWorkstationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListUsableWorkstationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_usable_workstations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_usable_workstations(self, response: workstations.ListUsableWorkstationsResponse) -> workstations.ListUsableWorkstationsResponse: - """Post-rpc interceptor for list_usable_workstations - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_list_workstation_clusters(self, request: workstations.ListWorkstationClustersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationClustersRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_workstation_clusters - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_workstation_clusters(self, response: workstations.ListWorkstationClustersResponse) -> workstations.ListWorkstationClustersResponse: - """Post-rpc interceptor for list_workstation_clusters - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_list_workstation_configs(self, request: workstations.ListWorkstationConfigsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationConfigsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_workstation_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_workstation_configs(self, response: workstations.ListWorkstationConfigsResponse) -> workstations.ListWorkstationConfigsResponse: - """Post-rpc interceptor for list_workstation_configs - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_list_workstations(self, request: workstations.ListWorkstationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.ListWorkstationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_workstations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_workstations(self, response: workstations.ListWorkstationsResponse) -> workstations.ListWorkstationsResponse: - """Post-rpc interceptor for list_workstations - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_start_workstation(self, request: workstations.StartWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.StartWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for start_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_start_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for start_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_stop_workstation(self, request: workstations.StopWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.StopWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for stop_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_stop_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for stop_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_update_workstation(self, request: workstations.UpdateWorkstationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_workstation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_update_workstation(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_workstation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_update_workstation_cluster(self, request: workstations.UpdateWorkstationClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_workstation_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_update_workstation_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_workstation_cluster - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_update_workstation_config(self, request: workstations.UpdateWorkstationConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[workstations.UpdateWorkstationConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_workstation_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_update_workstation_config(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_workstation_config - - Override in a subclass to manipulate the response - after it is returned by the Workstations 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 Workstations 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 Workstations 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 Workstations 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 Workstations 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 Workstations 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 Workstations server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_delete_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for delete_operation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Workstations server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Workstations server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class WorkstationsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: WorkstationsRestInterceptor - - -class WorkstationsRestTransport(WorkstationsTransport): - """REST backend transport for Workstations. - - Service for interacting with Cloud Workstations. - - 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 = 'workstations.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[WorkstationsRestInterceptor] = 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 WorkstationsRestInterceptor() - 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.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1beta") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateWorkstation(WorkstationsRestStub): - def __hash__(self): - return hash("CreateWorkstation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "workstationId" : "", } - - @classmethod - def _get_unset_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: workstations.CreateWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create workstation method over HTTP. - - Args: - request (~.workstations.CreateWorkstationRequest): - The request object. Message for creating a - CreateWorkstation. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): 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': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations', - 'body': 'workstation', - }, - ] - request, metadata = self._interceptor.pre_create_workstation(request, metadata) - pb_request = workstations.CreateWorkstationRequest.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_workstation(resp) - return resp - - class _CreateWorkstationCluster(WorkstationsRestStub): - def __hash__(self): - return hash("CreateWorkstationCluster") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "workstationClusterId" : "", } - - @classmethod - def _get_unset_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: workstations.CreateWorkstationClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create workstation - cluster method over HTTP. - - Args: - request (~.workstations.CreateWorkstationClusterRequest): - The request object. Message for creating a - CreateWorkstationCluster. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): 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': '/v1beta/{parent=projects/*/locations/*}/workstationClusters', - 'body': 'workstation_cluster', - }, - ] - request, metadata = self._interceptor.pre_create_workstation_cluster(request, metadata) - pb_request = workstations.CreateWorkstationClusterRequest.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_workstation_cluster(resp) - return resp - - class _CreateWorkstationConfig(WorkstationsRestStub): - def __hash__(self): - return hash("CreateWorkstationConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "workstationConfigId" : "", } - - @classmethod - def _get_unset_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: workstations.CreateWorkstationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create workstation config method over HTTP. - - Args: - request (~.workstations.CreateWorkstationConfigRequest): - The request object. Message for creating a - CreateWorkstationConfig. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): 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': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs', - 'body': 'workstation_config', - }, - ] - request, metadata = self._interceptor.pre_create_workstation_config(request, metadata) - pb_request = workstations.CreateWorkstationConfigRequest.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_workstation_config(resp) - return resp - - class _DeleteWorkstation(WorkstationsRestStub): - def __hash__(self): - return hash("DeleteWorkstation") - - __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: workstations.DeleteWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete workstation method over HTTP. - - Args: - request (~.workstations.DeleteWorkstationRequest): - The request object. Request message for - DeleteWorkstation. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_workstation(request, metadata) - pb_request = workstations.DeleteWorkstationRequest.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_workstation(resp) - return resp - - class _DeleteWorkstationCluster(WorkstationsRestStub): - def __hash__(self): - return hash("DeleteWorkstationCluster") - - __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: workstations.DeleteWorkstationClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete workstation - cluster method over HTTP. - - Args: - request (~.workstations.DeleteWorkstationClusterRequest): - The request object. Message for deleting a workstation - cluster. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_workstation_cluster(request, metadata) - pb_request = workstations.DeleteWorkstationClusterRequest.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_workstation_cluster(resp) - return resp - - class _DeleteWorkstationConfig(WorkstationsRestStub): - def __hash__(self): - return hash("DeleteWorkstationConfig") - - __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: workstations.DeleteWorkstationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete workstation config method over HTTP. - - Args: - request (~.workstations.DeleteWorkstationConfigRequest): - The request object. Message for deleting a workstation - configuration. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_workstation_config(request, metadata) - pb_request = workstations.DeleteWorkstationConfigRequest.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_workstation_config(resp) - return resp - - class _GenerateAccessToken(WorkstationsRestStub): - def __hash__(self): - return hash("GenerateAccessToken") - - __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: workstations.GenerateAccessTokenRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.GenerateAccessTokenResponse: - r"""Call the generate access token method over HTTP. - - Args: - request (~.workstations.GenerateAccessTokenRequest): - The request object. Request message for - GenerateAccessToken. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.workstations.GenerateAccessTokenResponse: - Response message for - GenerateAccessToken. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{workstation=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:generateAccessToken', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_generate_access_token(request, metadata) - pb_request = workstations.GenerateAccessTokenRequest.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 = workstations.GenerateAccessTokenResponse() - pb_resp = workstations.GenerateAccessTokenResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_generate_access_token(resp) - return resp - - class _GetWorkstation(WorkstationsRestStub): - def __hash__(self): - return hash("GetWorkstation") - - __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: workstations.GetWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.Workstation: - r"""Call the get workstation method over HTTP. - - Args: - request (~.workstations.GetWorkstationRequest): - The request object. Request message for GetWorkstation. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.workstations.Workstation: - A single instance of a developer - workstation with its own persistent - storage. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', - }, - ] - request, metadata = self._interceptor.pre_get_workstation(request, metadata) - pb_request = workstations.GetWorkstationRequest.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 = workstations.Workstation() - pb_resp = workstations.Workstation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_workstation(resp) - return resp - - class _GetWorkstationCluster(WorkstationsRestStub): - def __hash__(self): - return hash("GetWorkstationCluster") - - __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: workstations.GetWorkstationClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.WorkstationCluster: - r"""Call the get workstation cluster method over HTTP. - - Args: - request (~.workstations.GetWorkstationClusterRequest): - The request object. Request message for - GetWorkstationCluster. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.workstations.WorkstationCluster: - A grouping of workstation - configurations and the associated - workstations in that region. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/workstationClusters/*}', - }, - ] - request, metadata = self._interceptor.pre_get_workstation_cluster(request, metadata) - pb_request = workstations.GetWorkstationClusterRequest.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 = workstations.WorkstationCluster() - pb_resp = workstations.WorkstationCluster.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_workstation_cluster(resp) - return resp - - class _GetWorkstationConfig(WorkstationsRestStub): - def __hash__(self): - return hash("GetWorkstationConfig") - - __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: workstations.GetWorkstationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.WorkstationConfig: - r"""Call the get workstation config method over HTTP. - - Args: - request (~.workstations.GetWorkstationConfigRequest): - The request object. Request message for - GetWorkstationConfig. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.workstations.WorkstationConfig: - A set of configuration options - describing how a workstation will be - run. Workstation configurations are - intended to be shared across multiple - workstations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', - }, - ] - request, metadata = self._interceptor.pre_get_workstation_config(request, metadata) - pb_request = workstations.GetWorkstationConfigRequest.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 = workstations.WorkstationConfig() - pb_resp = workstations.WorkstationConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_workstation_config(resp) - return resp - - class _ListUsableWorkstationConfigs(WorkstationsRestStub): - def __hash__(self): - return hash("ListUsableWorkstationConfigs") - - __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: workstations.ListUsableWorkstationConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListUsableWorkstationConfigsResponse: - r"""Call the list usable workstation - configs method over HTTP. - - Args: - request (~.workstations.ListUsableWorkstationConfigsRequest): - The request object. Request message for - ListUsableWorkstationConfigs. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.workstations.ListUsableWorkstationConfigsResponse: - Response message for - ListUsableWorkstationConfigs. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs:listUsable', - }, - ] - request, metadata = self._interceptor.pre_list_usable_workstation_configs(request, metadata) - pb_request = workstations.ListUsableWorkstationConfigsRequest.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 = workstations.ListUsableWorkstationConfigsResponse() - pb_resp = workstations.ListUsableWorkstationConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_usable_workstation_configs(resp) - return resp - - class _ListUsableWorkstations(WorkstationsRestStub): - def __hash__(self): - return hash("ListUsableWorkstations") - - __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: workstations.ListUsableWorkstationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListUsableWorkstationsResponse: - r"""Call the list usable workstations method over HTTP. - - Args: - request (~.workstations.ListUsableWorkstationsRequest): - The request object. Request message for - ListUsableWorkstations. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.workstations.ListUsableWorkstationsResponse: - Response message for - ListUsableWorkstations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations:listUsable', - }, - ] - request, metadata = self._interceptor.pre_list_usable_workstations(request, metadata) - pb_request = workstations.ListUsableWorkstationsRequest.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 = workstations.ListUsableWorkstationsResponse() - pb_resp = workstations.ListUsableWorkstationsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_usable_workstations(resp) - return resp - - class _ListWorkstationClusters(WorkstationsRestStub): - def __hash__(self): - return hash("ListWorkstationClusters") - - __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: workstations.ListWorkstationClustersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListWorkstationClustersResponse: - r"""Call the list workstation clusters method over HTTP. - - Args: - request (~.workstations.ListWorkstationClustersRequest): - The request object. Request message for - ListWorkstationClusters. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.workstations.ListWorkstationClustersResponse: - Response message for - ListWorkstationClusters. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/locations/*}/workstationClusters', - }, - ] - request, metadata = self._interceptor.pre_list_workstation_clusters(request, metadata) - pb_request = workstations.ListWorkstationClustersRequest.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 = workstations.ListWorkstationClustersResponse() - pb_resp = workstations.ListWorkstationClustersResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_workstation_clusters(resp) - return resp - - class _ListWorkstationConfigs(WorkstationsRestStub): - def __hash__(self): - return hash("ListWorkstationConfigs") - - __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: workstations.ListWorkstationConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListWorkstationConfigsResponse: - r"""Call the list workstation configs method over HTTP. - - Args: - request (~.workstations.ListWorkstationConfigsRequest): - The request object. Request message for - ListWorkstationConfigs. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.workstations.ListWorkstationConfigsResponse: - Response message for - ListWorkstationConfigs. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs', - }, - ] - request, metadata = self._interceptor.pre_list_workstation_configs(request, metadata) - pb_request = workstations.ListWorkstationConfigsRequest.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 = workstations.ListWorkstationConfigsResponse() - pb_resp = workstations.ListWorkstationConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_workstation_configs(resp) - return resp - - class _ListWorkstations(WorkstationsRestStub): - def __hash__(self): - return hash("ListWorkstations") - - __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: workstations.ListWorkstationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> workstations.ListWorkstationsResponse: - r"""Call the list workstations method over HTTP. - - Args: - request (~.workstations.ListWorkstationsRequest): - The request object. Request message for ListWorkstations. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.workstations.ListWorkstationsResponse: - Response message for - ListWorkstations. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations', - }, - ] - request, metadata = self._interceptor.pre_list_workstations(request, metadata) - pb_request = workstations.ListWorkstationsRequest.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 = workstations.ListWorkstationsResponse() - pb_resp = workstations.ListWorkstationsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_workstations(resp) - return resp - - class _StartWorkstation(WorkstationsRestStub): - def __hash__(self): - return hash("StartWorkstation") - - __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: workstations.StartWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the start workstation method over HTTP. - - Args: - request (~.workstations.StartWorkstationRequest): - The request object. Request message for StartWorkstation. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:start', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_start_workstation(request, metadata) - pb_request = workstations.StartWorkstationRequest.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_start_workstation(resp) - return resp - - class _StopWorkstation(WorkstationsRestStub): - def __hash__(self): - return hash("StopWorkstation") - - __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: workstations.StopWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the stop workstation method over HTTP. - - Args: - request (~.workstations.StopWorkstationRequest): - The request object. Request message for StopWorkstation. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): 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': '/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:stop', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_stop_workstation(request, metadata) - pb_request = workstations.StopWorkstationRequest.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_stop_workstation(resp) - return resp - - class _UpdateWorkstation(WorkstationsRestStub): - def __hash__(self): - return hash("UpdateWorkstation") - - __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: workstations.UpdateWorkstationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update workstation method over HTTP. - - Args: - request (~.workstations.UpdateWorkstationRequest): - The request object. Request message for - UpdateWorkstation. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): 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': '/v1beta/{workstation.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}', - 'body': 'workstation', - }, - ] - request, metadata = self._interceptor.pre_update_workstation(request, metadata) - pb_request = workstations.UpdateWorkstationRequest.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_workstation(resp) - return resp - - class _UpdateWorkstationCluster(WorkstationsRestStub): - def __hash__(self): - return hash("UpdateWorkstationCluster") - - __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: workstations.UpdateWorkstationClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update workstation - cluster method over HTTP. - - Args: - request (~.workstations.UpdateWorkstationClusterRequest): - The request object. Request message for - UpdateWorkstationCluster. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): 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': '/v1beta/{workstation_cluster.name=projects/*/locations/*/workstationClusters/*}', - 'body': 'workstation_cluster', - }, - ] - request, metadata = self._interceptor.pre_update_workstation_cluster(request, metadata) - pb_request = workstations.UpdateWorkstationClusterRequest.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_workstation_cluster(resp) - return resp - - class _UpdateWorkstationConfig(WorkstationsRestStub): - def __hash__(self): - return hash("UpdateWorkstationConfig") - - __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: workstations.UpdateWorkstationConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update workstation config method over HTTP. - - Args: - request (~.workstations.UpdateWorkstationConfigRequest): - The request object. Request message for - UpdateWorkstationConfig. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): 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': '/v1beta/{workstation_config.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}', - 'body': 'workstation_config', - }, - ] - request, metadata = self._interceptor.pre_update_workstation_config(request, metadata) - pb_request = workstations.UpdateWorkstationConfigRequest.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_workstation_config(resp) - return resp - - @property - def create_workstation(self) -> Callable[ - [workstations.CreateWorkstationRequest], - 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._CreateWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_workstation_cluster(self) -> Callable[ - [workstations.CreateWorkstationClusterRequest], - 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._CreateWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_workstation_config(self) -> Callable[ - [workstations.CreateWorkstationConfigRequest], - 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._CreateWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_workstation(self) -> Callable[ - [workstations.DeleteWorkstationRequest], - 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._DeleteWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_workstation_cluster(self) -> Callable[ - [workstations.DeleteWorkstationClusterRequest], - 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._DeleteWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_workstation_config(self) -> Callable[ - [workstations.DeleteWorkstationConfigRequest], - 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._DeleteWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def generate_access_token(self) -> Callable[ - [workstations.GenerateAccessTokenRequest], - workstations.GenerateAccessTokenResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GenerateAccessToken(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_workstation(self) -> Callable[ - [workstations.GetWorkstationRequest], - workstations.Workstation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_workstation_cluster(self) -> Callable[ - [workstations.GetWorkstationClusterRequest], - workstations.WorkstationCluster]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_workstation_config(self) -> Callable[ - [workstations.GetWorkstationConfigRequest], - workstations.WorkstationConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_usable_workstation_configs(self) -> Callable[ - [workstations.ListUsableWorkstationConfigsRequest], - workstations.ListUsableWorkstationConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListUsableWorkstationConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_usable_workstations(self) -> Callable[ - [workstations.ListUsableWorkstationsRequest], - workstations.ListUsableWorkstationsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListUsableWorkstations(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_workstation_clusters(self) -> Callable[ - [workstations.ListWorkstationClustersRequest], - workstations.ListWorkstationClustersResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListWorkstationClusters(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_workstation_configs(self) -> Callable[ - [workstations.ListWorkstationConfigsRequest], - workstations.ListWorkstationConfigsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListWorkstationConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_workstations(self) -> Callable[ - [workstations.ListWorkstationsRequest], - workstations.ListWorkstationsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListWorkstations(self._session, self._host, self._interceptor) # type: ignore - - @property - def start_workstation(self) -> Callable[ - [workstations.StartWorkstationRequest], - 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._StartWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def stop_workstation(self) -> Callable[ - [workstations.StopWorkstationRequest], - 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._StopWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_workstation(self) -> Callable[ - [workstations.UpdateWorkstationRequest], - 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._UpdateWorkstation(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_workstation_cluster(self) -> Callable[ - [workstations.UpdateWorkstationClusterRequest], - 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._UpdateWorkstationCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_workstation_config(self) -> Callable[ - [workstations.UpdateWorkstationConfigRequest], - 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._UpdateWorkstationConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(WorkstationsRestStub): - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:getIamPolicy', - }, - ] - - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(WorkstationsRestStub): - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:setIamPolicy', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - 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) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(WorkstationsRestStub): - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1beta/{resource=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:testIamPermissions', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - 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) - - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(WorkstationsRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - 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 self._interceptor.post_cancel_operation(None) - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(WorkstationsRestStub): - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object for DeleteOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_delete_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(WorkstationsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(WorkstationsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'WorkstationsRestTransport', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/__init__.py deleted file mode 100644 index 78e68e36bfd4..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/__init__.py +++ /dev/null @@ -1,80 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .workstations import ( - CreateWorkstationClusterRequest, - CreateWorkstationConfigRequest, - CreateWorkstationRequest, - DeleteWorkstationClusterRequest, - DeleteWorkstationConfigRequest, - DeleteWorkstationRequest, - GenerateAccessTokenRequest, - GenerateAccessTokenResponse, - GetWorkstationClusterRequest, - GetWorkstationConfigRequest, - GetWorkstationRequest, - ListUsableWorkstationConfigsRequest, - ListUsableWorkstationConfigsResponse, - ListUsableWorkstationsRequest, - ListUsableWorkstationsResponse, - ListWorkstationClustersRequest, - ListWorkstationClustersResponse, - ListWorkstationConfigsRequest, - ListWorkstationConfigsResponse, - ListWorkstationsRequest, - ListWorkstationsResponse, - OperationMetadata, - StartWorkstationRequest, - StopWorkstationRequest, - UpdateWorkstationClusterRequest, - UpdateWorkstationConfigRequest, - UpdateWorkstationRequest, - Workstation, - WorkstationCluster, - WorkstationConfig, -) - -__all__ = ( - 'CreateWorkstationClusterRequest', - 'CreateWorkstationConfigRequest', - 'CreateWorkstationRequest', - 'DeleteWorkstationClusterRequest', - 'DeleteWorkstationConfigRequest', - 'DeleteWorkstationRequest', - 'GenerateAccessTokenRequest', - 'GenerateAccessTokenResponse', - 'GetWorkstationClusterRequest', - 'GetWorkstationConfigRequest', - 'GetWorkstationRequest', - 'ListUsableWorkstationConfigsRequest', - 'ListUsableWorkstationConfigsResponse', - 'ListUsableWorkstationsRequest', - 'ListUsableWorkstationsResponse', - 'ListWorkstationClustersRequest', - 'ListWorkstationClustersResponse', - 'ListWorkstationConfigsRequest', - 'ListWorkstationConfigsResponse', - 'ListWorkstationsRequest', - 'ListWorkstationsResponse', - 'OperationMetadata', - 'StartWorkstationRequest', - 'StopWorkstationRequest', - 'UpdateWorkstationClusterRequest', - 'UpdateWorkstationConfigRequest', - 'UpdateWorkstationRequest', - 'Workstation', - 'WorkstationCluster', - 'WorkstationConfig', -) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/workstations.py b/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/workstations.py deleted file mode 100644 index 7d9845c50b8d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/google/cloud/workstations_v1beta/types/workstations.py +++ /dev/null @@ -1,1793 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.workstations.v1beta', - manifest={ - 'WorkstationCluster', - 'WorkstationConfig', - 'Workstation', - 'GetWorkstationClusterRequest', - 'ListWorkstationClustersRequest', - 'ListWorkstationClustersResponse', - 'CreateWorkstationClusterRequest', - 'UpdateWorkstationClusterRequest', - 'DeleteWorkstationClusterRequest', - 'GetWorkstationConfigRequest', - 'ListWorkstationConfigsRequest', - 'ListWorkstationConfigsResponse', - 'ListUsableWorkstationConfigsRequest', - 'ListUsableWorkstationConfigsResponse', - 'CreateWorkstationConfigRequest', - 'UpdateWorkstationConfigRequest', - 'DeleteWorkstationConfigRequest', - 'GetWorkstationRequest', - 'ListWorkstationsRequest', - 'ListWorkstationsResponse', - 'ListUsableWorkstationsRequest', - 'ListUsableWorkstationsResponse', - 'CreateWorkstationRequest', - 'UpdateWorkstationRequest', - 'DeleteWorkstationRequest', - 'StartWorkstationRequest', - 'StopWorkstationRequest', - 'GenerateAccessTokenRequest', - 'GenerateAccessTokenResponse', - 'OperationMetadata', - }, -) - - -class WorkstationCluster(proto.Message): - r"""A grouping of workstation configurations and the associated - workstations in that region. - - Attributes: - name (str): - Full name of this resource. - display_name (str): - Human-readable name for this resource. - uid (str): - Output only. A system-assigned unique - identified for this resource. - reconciling (bool): - Output only. Indicates whether this resource - is currently being updated to match its intended - state. - annotations (MutableMapping[str, str]): - Client-specified annotations. - labels (MutableMapping[str, str]): - Client-specified labels that are applied to - the resource and that are also propagated to the - underlying Compute Engine resources. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this resource was - created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this resource was most - recently updated. - delete_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this resource was - soft-deleted. - etag (str): - Checksum computed by the server. May be sent - on update and delete requests to make sure that - the client has an up-to-date value before - proceeding. - network (str): - Immutable. Name of the Compute Engine network - in which instances associated with this cluster - will be created. - subnetwork (str): - Immutable. Name of the Compute Engine - subnetwork in which instances associated with - this cluster will be created. Must be part of - the subnetwork specified for this cluster. - control_plane_ip (str): - Output only. The private IP address of the - control plane for this cluster. Workstation VMs - need access to this IP address to work with the - service, so make sure that your firewall rules - allow egress from the workstation VMs to this - address. - private_cluster_config (google.cloud.workstations_v1beta.types.WorkstationCluster.PrivateClusterConfig): - Configuration for private cluster. - degraded (bool): - Output only. Whether this resource is in degraded mode, in - which case it may require user action to restore full - functionality. Details can be found in the ``conditions`` - field. - conditions (MutableSequence[google.rpc.status_pb2.Status]): - Output only. Status conditions describing the - current resource state. - """ - - class PrivateClusterConfig(proto.Message): - r"""Configuration options for private clusters. - - Attributes: - enable_private_endpoint (bool): - Immutable. Whether Workstations endpoint is - private. - cluster_hostname (str): - Output only. Hostname for the workstation - cluster. This field will be populated only when - private endpoint is enabled. To access - workstations in the cluster, create a new DNS - zone mapping this domain name to an internal IP - address and a forwarding rule mapping that - address to the service attachment. - service_attachment_uri (str): - Output only. Service attachment URI for the workstation - cluster. The service attachemnt is created when private - endpoint is enabled. To access workstations in the cluster, - configure access to the managed service using `Private - Service - Connect `__. - allowed_projects (MutableSequence[str]): - Additional projects that are allowed to - attach to the workstation cluster's service - attachment. By default, the workstation - cluster's project and the VPC host project (if - different) are allowed. - """ - - enable_private_endpoint: bool = proto.Field( - proto.BOOL, - number=1, - ) - cluster_hostname: str = proto.Field( - proto.STRING, - number=2, - ) - service_attachment_uri: str = proto.Field( - proto.STRING, - number=3, - ) - allowed_projects: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - uid: str = proto.Field( - proto.STRING, - number=3, - ) - reconciling: bool = proto.Field( - proto.BOOL, - number=4, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=15, - ) - 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, - ) - network: str = proto.Field( - proto.STRING, - number=10, - ) - subnetwork: str = proto.Field( - proto.STRING, - number=11, - ) - control_plane_ip: str = proto.Field( - proto.STRING, - number=16, - ) - private_cluster_config: PrivateClusterConfig = proto.Field( - proto.MESSAGE, - number=12, - message=PrivateClusterConfig, - ) - degraded: bool = proto.Field( - proto.BOOL, - number=13, - ) - conditions: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=status_pb2.Status, - ) - - -class WorkstationConfig(proto.Message): - r"""A set of configuration options describing how a workstation - will be run. Workstation configurations are intended to be - shared across multiple workstations. - - Attributes: - name (str): - Full name of this resource. - display_name (str): - Human-readable name for this resource. - uid (str): - Output only. A system-assigned unique - identified for this resource. - reconciling (bool): - Output only. Indicates whether this resource - is currently being updated to match its intended - state. - annotations (MutableMapping[str, str]): - Client-specified annotations. - labels (MutableMapping[str, str]): - Client-specified labels that are applied to - the resource and that are also propagated to the - underlying Compute Engine resources. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this resource was - created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this resource was most - recently updated. - delete_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this resource was - soft-deleted. - etag (str): - Checksum computed by the server. May be sent - on update and delete requests to make sure that - the client has an up-to-date value before - proceeding. - idle_timeout (google.protobuf.duration_pb2.Duration): - How long to wait before automatically - stopping an instance that hasn't received any - user traffic. A value of 0 indicates that this - instance should never time out due to idleness. - Defaults to 20 minutes. - running_timeout (google.protobuf.duration_pb2.Duration): - How long to wait before automatically stopping a workstation - after it started. A value of 0 indicates that workstations - using this configuration should never time out. Must be - greater than 0 and less than 24 hours if encryption_key is - set. Defaults to 12 hours. - host (google.cloud.workstations_v1beta.types.WorkstationConfig.Host): - Runtime host for the workstation. - persistent_directories (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig.PersistentDirectory]): - Directories to persist across workstation - sessions. - container (google.cloud.workstations_v1beta.types.WorkstationConfig.Container): - Container that will be run for each - workstation using this configuration when that - workstation is started. - encryption_key (google.cloud.workstations_v1beta.types.WorkstationConfig.CustomerEncryptionKey): - Immutable. Encrypts resources of this - workstation configuration using a - customer-managed encryption key. - If specified, the boot disk of the Compute - Engine instance and the persistent disk are - encrypted using this encryption key. If this - field is not set, the disks are encrypted using - a generated key. Customer-managed encryption - keys do not protect disk metadata. - If the customer-managed encryption key is - rotated, when the workstation instance is - stopped, the system attempts to recreate the - persistent disk with the new version of the key. - Be sure to keep older versions of the key until - the persistent disk is recreated. Otherwise, - data on the persistent disk will be lost. - If the encryption key is revoked, the - workstation session will automatically be - stopped within 7 hours. - - Immutable after the workstation configuration is - created. - readiness_checks (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig.ReadinessCheck]): - Readiness checks to perform when starting a - workstation using this workstation - configuration. Mark a workstation as running - only after all specified readiness checks return - 200 status codes. - degraded (bool): - Output only. Whether this resource is in degraded mode, in - which case it may require user action to restore full - functionality. Details can be found in the ``conditions`` - field. - conditions (MutableSequence[google.rpc.status_pb2.Status]): - Output only. Status conditions describing the - current resource state. - enable_audit_agent (bool): - Whether to enable linux auditd logging on the workstation. - When enabled, a service account must also be specified that - has logging.buckets.write permission on the project. - Operating system audit logging is distinct from `Cloud Audit - Logs `__. - """ - - class Host(proto.Message): - r"""Runtime host for a workstation. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gce_instance (google.cloud.workstations_v1beta.types.WorkstationConfig.Host.GceInstance): - Specifies a Compute Engine instance as the - host. - - This field is a member of `oneof`_ ``config``. - """ - - class GceInstance(proto.Message): - r"""A runtime using a Compute Engine instance. - - Attributes: - machine_type (str): - The name of a Compute Engine machine type. - service_account (str): - Email address of the service account used on - VM instances used to support this configuration. - If not set, VMs run with a Google-managed - service account. This service account must have - permission to pull the specified container - image; otherwise, the image must be publicly - accessible. - tags (MutableSequence[str]): - Network tags to add to the Compute Engine - machines backing the Workstations. - pool_size (int): - Number of instances to pool for faster - workstation startup. - pooled_instances (int): - Output only. Number of instances currently - available in the pool for faster workstation - startup. - disable_public_ip_addresses (bool): - Whether instances have no public IP address. - shielded_instance_config (google.cloud.workstations_v1beta.types.WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig): - A set of Compute Engine Shielded instance - options. - confidential_instance_config (google.cloud.workstations_v1beta.types.WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig): - A set of Compute Engine Confidential VM - instance options. - boot_disk_size_gb (int): - Size of the boot disk in GB. Defaults to 50. - accelerators (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig.Host.GceInstance.Accelerator]): - A list of the type and count of accelerator - cards attached to the instance. - """ - - class GceShieldedInstanceConfig(proto.Message): - r"""A set of Compute Engine Shielded instance options. - - Attributes: - enable_secure_boot (bool): - Whether the instance has Secure Boot enabled. - enable_vtpm (bool): - Whether the instance has the vTPM enabled. - enable_integrity_monitoring (bool): - Whether the instance has integrity monitoring - enabled. - """ - - enable_secure_boot: bool = proto.Field( - proto.BOOL, - number=1, - ) - enable_vtpm: bool = proto.Field( - proto.BOOL, - number=2, - ) - enable_integrity_monitoring: bool = proto.Field( - proto.BOOL, - number=3, - ) - - class GceConfidentialInstanceConfig(proto.Message): - r"""A set of Compute Engine Confidential VM instance options. - - Attributes: - enable_confidential_compute (bool): - Whether the instance has confidential compute - enabled. - """ - - enable_confidential_compute: bool = proto.Field( - proto.BOOL, - number=1, - ) - - class Accelerator(proto.Message): - r"""An accelerator card attached to the instance. - - Attributes: - type_ (str): - Type of accelerator resource to attach to the - instance, for example, "nvidia-tesla-p100". - count (int): - Number of accelerator cards exposed to the - instance. - """ - - type_: str = proto.Field( - proto.STRING, - number=1, - ) - count: int = proto.Field( - proto.INT32, - number=2, - ) - - machine_type: str = proto.Field( - proto.STRING, - number=1, - ) - service_account: str = proto.Field( - proto.STRING, - number=2, - ) - tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - pool_size: int = proto.Field( - proto.INT32, - number=5, - ) - pooled_instances: int = proto.Field( - proto.INT32, - number=12, - ) - disable_public_ip_addresses: bool = proto.Field( - proto.BOOL, - number=6, - ) - shielded_instance_config: 'WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig' = proto.Field( - proto.MESSAGE, - number=8, - message='WorkstationConfig.Host.GceInstance.GceShieldedInstanceConfig', - ) - confidential_instance_config: 'WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig' = proto.Field( - proto.MESSAGE, - number=10, - message='WorkstationConfig.Host.GceInstance.GceConfidentialInstanceConfig', - ) - boot_disk_size_gb: int = proto.Field( - proto.INT32, - number=9, - ) - accelerators: MutableSequence['WorkstationConfig.Host.GceInstance.Accelerator'] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message='WorkstationConfig.Host.GceInstance.Accelerator', - ) - - gce_instance: 'WorkstationConfig.Host.GceInstance' = proto.Field( - proto.MESSAGE, - number=1, - oneof='config', - message='WorkstationConfig.Host.GceInstance', - ) - - class PersistentDirectory(proto.Message): - r"""A directory to persist across workstation sessions. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - mount_path (str): - Location of this directory in the running - workstation. - gce_pd (google.cloud.workstations_v1beta.types.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk): - A PersistentDirectory backed by a Compute - Engine persistent disk. - - This field is a member of `oneof`_ ``directory_type``. - """ - - class GceRegionalPersistentDisk(proto.Message): - r"""A PersistentDirectory backed by a Compute Engine regional - persistent disk. - - Attributes: - size_gb (int): - Size of the disk in GB. Must be empty if source_snapshot is - set. Defaults to 200. - fs_type (str): - Type of file system that the disk should be formatted with. - The workstation image must support this file system type. - Must be empty if source_snapshot is set. Defaults to ext4. - disk_type (str): - Type of the disk to use. Defaults to - pd-standard. - source_snapshot (str): - Name of the snapshot to use as the source for the disk. If - set, size_gb and fs_type must be empty. - reclaim_policy (google.cloud.workstations_v1beta.types.WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy): - What should happen to the disk after the - workstation is deleted. Defaults to DELETE. - """ - class ReclaimPolicy(proto.Enum): - r"""Value representing what should happen to the disk after the - workstation is deleted. - - Values: - RECLAIM_POLICY_UNSPECIFIED (0): - Do not use. - DELETE (1): - The persistent disk will be deleted with the - workstation. - RETAIN (2): - The persistent disk will be remain after the - workstation is deleted, and the administrator - must manually delete the disk. - """ - RECLAIM_POLICY_UNSPECIFIED = 0 - DELETE = 1 - RETAIN = 2 - - size_gb: int = proto.Field( - proto.INT32, - number=1, - ) - fs_type: str = proto.Field( - proto.STRING, - number=2, - ) - disk_type: str = proto.Field( - proto.STRING, - number=3, - ) - source_snapshot: str = proto.Field( - proto.STRING, - number=5, - ) - reclaim_policy: 'WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy' = proto.Field( - proto.ENUM, - number=4, - enum='WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk.ReclaimPolicy', - ) - - mount_path: str = proto.Field( - proto.STRING, - number=1, - ) - gce_pd: 'WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk' = proto.Field( - proto.MESSAGE, - number=2, - oneof='directory_type', - message='WorkstationConfig.PersistentDirectory.GceRegionalPersistentDisk', - ) - - class Container(proto.Message): - r"""A Docker container. - - Attributes: - image (str): - Docker image defining the container. This - image must be accessible by the service account - specified in the workstation configuration. - command (MutableSequence[str]): - If set, overrides the default ENTRYPOINT - specified by the image. - args (MutableSequence[str]): - Arguments passed to the entrypoint. - env (MutableMapping[str, str]): - Environment variables passed to the - container's entrypoint. - working_dir (str): - If set, overrides the default DIR specified - by the image. - run_as_user (int): - If set, overrides the USER specified in the - image with the given uid. - """ - - image: str = proto.Field( - proto.STRING, - number=1, - ) - command: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - args: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - env: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - working_dir: str = proto.Field( - proto.STRING, - number=5, - ) - run_as_user: int = proto.Field( - proto.INT32, - number=6, - ) - - class CustomerEncryptionKey(proto.Message): - r"""A customer-managed encryption key for the Compute Engine - resources of this workstation configuration. - - Attributes: - kms_key (str): - Immutable. The name of the Google Cloud KMS encryption key. - For example, - ``projects/PROJECT_ID/locations/REGION/keyRings/KEY_RING/cryptoKeys/KEY_NAME``. - kms_key_service_account (str): - Immutable. The service account to use with the specified KMS - key. We recommend that you use a separate service account - and follow KMS best practices. For more information, see - `Separation of - duties `__ - and ``gcloud kms keys add-iam-policy-binding`` - ```--member`` `__. - """ - - kms_key: str = proto.Field( - proto.STRING, - number=1, - ) - kms_key_service_account: str = proto.Field( - proto.STRING, - number=2, - ) - - class ReadinessCheck(proto.Message): - r"""A readiness check to be performed on a workstation. - - Attributes: - path (str): - Path to which the request should be sent. - port (int): - Port to which the request should be sent. - """ - - path: str = proto.Field( - proto.STRING, - number=1, - ) - port: int = proto.Field( - proto.INT32, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - uid: str = proto.Field( - proto.STRING, - number=3, - ) - reconciling: bool = proto.Field( - proto.BOOL, - number=4, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=18, - ) - 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, - ) - idle_timeout: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=10, - message=duration_pb2.Duration, - ) - running_timeout: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=11, - message=duration_pb2.Duration, - ) - host: Host = proto.Field( - proto.MESSAGE, - number=12, - message=Host, - ) - persistent_directories: MutableSequence[PersistentDirectory] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message=PersistentDirectory, - ) - container: Container = proto.Field( - proto.MESSAGE, - number=14, - message=Container, - ) - encryption_key: CustomerEncryptionKey = proto.Field( - proto.MESSAGE, - number=17, - message=CustomerEncryptionKey, - ) - readiness_checks: MutableSequence[ReadinessCheck] = proto.RepeatedField( - proto.MESSAGE, - number=19, - message=ReadinessCheck, - ) - degraded: bool = proto.Field( - proto.BOOL, - number=15, - ) - conditions: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=16, - message=status_pb2.Status, - ) - enable_audit_agent: bool = proto.Field( - proto.BOOL, - number=20, - ) - - -class Workstation(proto.Message): - r"""A single instance of a developer workstation with its own - persistent storage. - - Attributes: - name (str): - Full name of this resource. - display_name (str): - Human-readable name for this resource. - uid (str): - Output only. A system-assigned unique - identified for this resource. - reconciling (bool): - Output only. Indicates whether this resource - is currently being updated to match its intended - state. - annotations (MutableMapping[str, str]): - Client-specified annotations. - labels (MutableMapping[str, str]): - Client-specified labels that are applied to - the resource and that are also propagated to the - underlying Compute Engine resources. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this resource was - created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this resource was most - recently updated. - delete_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when this resource was - soft-deleted. - etag (str): - Checksum computed by the server. May be sent - on update and delete requests to make sure that - the client has an up-to-date value before - proceeding. - state (google.cloud.workstations_v1beta.types.Workstation.State): - Output only. Current state of the - workstation. - host (str): - Output only. Host to which clients can send HTTPS traffic - that will be received by the workstation. Authorized traffic - will be received to the workstation as HTTP on port 80. To - send traffic to a different port, clients may prefix the - host with the destination port in the format - ``{port}-{host}``. - env (MutableMapping[str, str]): - Environment variables passed to the - workstation container's entrypoint. - """ - class State(proto.Enum): - r"""Whether a workstation is running and ready to receive user - requests. - - Values: - STATE_UNSPECIFIED (0): - Do not use. - STATE_STARTING (1): - The workstation is not yet ready to accept - requests from users but will be soon. - STATE_RUNNING (2): - The workstation is ready to accept requests - from users. - STATE_STOPPING (3): - The workstation is being stopped. - STATE_STOPPED (4): - The workstation is stopped and will not be - able to receive requests until it is started. - """ - STATE_UNSPECIFIED = 0 - STATE_STARTING = 1 - STATE_RUNNING = 2 - STATE_STOPPING = 3 - STATE_STOPPED = 4 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - uid: str = proto.Field( - proto.STRING, - number=3, - ) - reconciling: bool = proto.Field( - proto.BOOL, - number=4, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=13, - ) - 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, - ) - state: State = proto.Field( - proto.ENUM, - number=10, - enum=State, - ) - host: str = proto.Field( - proto.STRING, - number=11, - ) - env: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=12, - ) - - -class GetWorkstationClusterRequest(proto.Message): - r"""Request message for GetWorkstationCluster. - - Attributes: - name (str): - Required. Name of the requested resource. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListWorkstationClustersRequest(proto.Message): - r"""Request message for ListWorkstationClusters. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Maximum number of items to return. - page_token (str): - next_page_token value returned from a previous List request, - if any. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListWorkstationClustersResponse(proto.Message): - r"""Response message for ListWorkstationClusters. - - Attributes: - workstation_clusters (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationCluster]): - The requested workstation clusters. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstation_clusters: MutableSequence['WorkstationCluster'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='WorkstationCluster', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateWorkstationClusterRequest(proto.Message): - r"""Message for creating a CreateWorkstationCluster. - - Attributes: - parent (str): - Required. Parent resource name. - workstation_cluster_id (str): - Required. ID to use for the workstation - cluster. - workstation_cluster (google.cloud.workstations_v1beta.types.WorkstationCluster): - Required. Workstation cluster to create. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - workstation_cluster_id: str = proto.Field( - proto.STRING, - number=2, - ) - workstation_cluster: 'WorkstationCluster' = proto.Field( - proto.MESSAGE, - number=3, - message='WorkstationCluster', - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateWorkstationClusterRequest(proto.Message): - r"""Request message for UpdateWorkstationCluster. - - Attributes: - workstation_cluster (google.cloud.workstations_v1beta.types.WorkstationCluster): - Required. Workstation cluster to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask that specifies which fields in - the workstation cluster should be updated. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - allow_missing (bool): - If set, and the workstation cluster is not found, a new - workstation cluster will be created. In this situation, - update_mask is ignored. - """ - - workstation_cluster: 'WorkstationCluster' = proto.Field( - proto.MESSAGE, - number=1, - message='WorkstationCluster', - ) - 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, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class DeleteWorkstationClusterRequest(proto.Message): - r"""Message for deleting a workstation cluster. - - Attributes: - name (str): - Required. Name of the workstation cluster to - delete. - validate_only (bool): - If set, validate the request and preview the - review, but do not apply it. - etag (str): - If set, the request will be rejected if the - latest version of the workstation cluster on the - server does not have this ETag. - force (bool): - If set, any workstation configurations and - workstations in the workstation cluster are also - deleted. Otherwise, the request only works if - the workstation cluster has no configurations or - workstations. - """ - - 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, - ) - force: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetWorkstationConfigRequest(proto.Message): - r"""Request message for GetWorkstationConfig. - - Attributes: - name (str): - Required. Name of the requested resource. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListWorkstationConfigsRequest(proto.Message): - r"""Request message for ListWorkstationConfigs. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Maximum number of items to return. - page_token (str): - next_page_token value returned from a previous List request, - if any. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListWorkstationConfigsResponse(proto.Message): - r"""Response message for ListWorkstationConfigs. - - Attributes: - workstation_configs (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig]): - The requested configs. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstation_configs: MutableSequence['WorkstationConfig'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='WorkstationConfig', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class ListUsableWorkstationConfigsRequest(proto.Message): - r"""Request message for ListUsableWorkstationConfigs. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Maximum number of items to return. - page_token (str): - next_page_token value returned from a previous List request, - if any. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListUsableWorkstationConfigsResponse(proto.Message): - r"""Response message for ListUsableWorkstationConfigs. - - Attributes: - workstation_configs (MutableSequence[google.cloud.workstations_v1beta.types.WorkstationConfig]): - The requested configs. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstation_configs: MutableSequence['WorkstationConfig'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='WorkstationConfig', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateWorkstationConfigRequest(proto.Message): - r"""Message for creating a CreateWorkstationConfig. - - Attributes: - parent (str): - Required. Parent resource name. - workstation_config_id (str): - Required. ID to use for the workstation - configuration. - workstation_config (google.cloud.workstations_v1beta.types.WorkstationConfig): - Required. Config to create. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - workstation_config_id: str = proto.Field( - proto.STRING, - number=2, - ) - workstation_config: 'WorkstationConfig' = proto.Field( - proto.MESSAGE, - number=3, - message='WorkstationConfig', - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateWorkstationConfigRequest(proto.Message): - r"""Request message for UpdateWorkstationConfig. - - Attributes: - workstation_config (google.cloud.workstations_v1beta.types.WorkstationConfig): - Required. Config to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask specifying which fields in the - workstation configuration should be updated. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - allow_missing (bool): - If set and the workstation configuration is not found, a new - workstation configuration will be created. In this - situation, update_mask is ignored. - """ - - workstation_config: 'WorkstationConfig' = proto.Field( - proto.MESSAGE, - number=1, - message='WorkstationConfig', - ) - 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, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class DeleteWorkstationConfigRequest(proto.Message): - r"""Message for deleting a workstation configuration. - - Attributes: - name (str): - Required. Name of the workstation - configuration to delete. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - etag (str): - If set, the request is rejected if the latest - version of the workstation configuration on the - server does not have this ETag. - force (bool): - If set, any workstations in the workstation - configuration are also deleted. Otherwise, the - request works only if the workstation - configuration has no workstations. - """ - - 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, - ) - force: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class GetWorkstationRequest(proto.Message): - r"""Request message for GetWorkstation. - - Attributes: - name (str): - Required. Name of the requested resource. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListWorkstationsRequest(proto.Message): - r"""Request message for ListWorkstations. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Maximum number of items to return. - page_token (str): - next_page_token value returned from a previous List request, - if any. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListWorkstationsResponse(proto.Message): - r"""Response message for ListWorkstations. - - Attributes: - workstations (MutableSequence[google.cloud.workstations_v1beta.types.Workstation]): - The requested workstations. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstations: MutableSequence['Workstation'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Workstation', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class ListUsableWorkstationsRequest(proto.Message): - r"""Request message for ListUsableWorkstations. - - Attributes: - parent (str): - Required. Parent resource name. - page_size (int): - Maximum number of items to return. - page_token (str): - next_page_token value returned from a previous List request, - if any. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListUsableWorkstationsResponse(proto.Message): - r"""Response message for ListUsableWorkstations. - - Attributes: - workstations (MutableSequence[google.cloud.workstations_v1beta.types.Workstation]): - The requested workstations. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results in the - list. - unreachable (MutableSequence[str]): - Unreachable resources. - """ - - @property - def raw_page(self): - return self - - workstations: MutableSequence['Workstation'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Workstation', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateWorkstationRequest(proto.Message): - r"""Message for creating a CreateWorkstation. - - Attributes: - parent (str): - Required. Parent resource name. - workstation_id (str): - Required. ID to use for the workstation. - workstation (google.cloud.workstations_v1beta.types.Workstation): - Required. Workstation to create. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - workstation_id: str = proto.Field( - proto.STRING, - number=2, - ) - workstation: 'Workstation' = proto.Field( - proto.MESSAGE, - number=3, - message='Workstation', - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class UpdateWorkstationRequest(proto.Message): - r"""Request message for UpdateWorkstation. - - Attributes: - workstation (google.cloud.workstations_v1beta.types.Workstation): - Required. Workstation to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Mask specifying which fields in the - workstation configuration should be updated. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - allow_missing (bool): - If set and the workstation configuration is not found, a new - workstation configuration is created. In this situation, - update_mask is ignored. - """ - - workstation: 'Workstation' = proto.Field( - proto.MESSAGE, - number=1, - message='Workstation', - ) - 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, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class DeleteWorkstationRequest(proto.Message): - r"""Request message for DeleteWorkstation. - - Attributes: - name (str): - Required. Name of the workstation to delete. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - etag (str): - If set, the request will be rejected if the - latest version of the workstation on the server - does not have this ETag. - """ - - 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 StartWorkstationRequest(proto.Message): - r"""Request message for StartWorkstation. - - Attributes: - name (str): - Required. Name of the workstation to start. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - etag (str): - If set, the request will be rejected if the - latest version of the workstation on the server - does not have this ETag. - """ - - 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 StopWorkstationRequest(proto.Message): - r"""Request message for StopWorkstation. - - Attributes: - name (str): - Required. Name of the workstation to stop. - validate_only (bool): - If set, validate the request and preview the - review, but do not actually apply it. - etag (str): - If set, the request will be rejected if the - latest version of the workstation on the server - does not have this ETag. - """ - - 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 GenerateAccessTokenRequest(proto.Message): - r"""Request message for GenerateAccessToken. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - workstation (str): - Required. Name of the workstation for which - the access token should be generated. - expire_time (google.protobuf.timestamp_pb2.Timestamp): - Desired expiration time of the access token. - This value must be at most 24 hours in the - future. If a value is not specified, the token's - expiration time will be set to a default value - of 1 hour in the future. - - This field is a member of `oneof`_ ``expiration``. - ttl (google.protobuf.duration_pb2.Duration): - Desired lifetime duration of the access - token. This value must be at most 24 hours. If a - value is not specified, the token's lifetime - will be set to a default value of 1 hour. - - This field is a member of `oneof`_ ``expiration``. - """ - - workstation: str = proto.Field( - proto.STRING, - number=1, - ) - expire_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - oneof='expiration', - message=timestamp_pb2.Timestamp, - ) - ttl: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - oneof='expiration', - message=duration_pb2.Duration, - ) - - -class GenerateAccessTokenResponse(proto.Message): - r"""Response message for GenerateAccessToken. - - Attributes: - access_token (str): - The generated bearer access token. To use this token, - include it in an Authorization header of an HTTP request - sent to the associated workstation's hostname—for example, - ``Authorization: Bearer ``. - expire_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which the generated token will - expire. - """ - - access_token: str = proto.Field( - proto.STRING, - number=1, - ) - expire_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class OperationMetadata(proto.Message): - r"""Metadata for long-running operations. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time that the operation was - created. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time that the operation finished - running. - target (str): - Output only. Server-defined resource path for - the target of the operation. - verb (str): - Output only. Name of the verb executed by the - operation. - status_message (str): - Output only. Human-readable status of the - operation, if any. - requested_cancellation (bool): - Output only. Identifies whether the user has - requested cancellation of the operation. - api_version (str): - Output only. API version used to start the - operation. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - target: str = proto.Field( - proto.STRING, - number=3, - ) - verb: str = proto.Field( - proto.STRING, - number=4, - ) - status_message: str = proto.Field( - proto.STRING, - number=5, - ) - requested_cancellation: bool = proto.Field( - proto.BOOL, - number=6, - ) - api_version: str = proto.Field( - proto.STRING, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/mypy.ini b/owl-bot-staging/google-cloud-workstations/v1beta/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/noxfile.py b/owl-bot-staging/google-cloud-workstations/v1beta/noxfile.py deleted file mode 100644 index 3f0ab930ba46..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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/workstations_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json deleted file mode 100644 index 8afcd1793b5c..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json +++ /dev/null @@ -1,3307 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.workstations.v1beta", - "version": "v1beta" - } - ], - "language": "PYTHON", - "name": "google-cloud-workstations", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.create_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.CreateWorkstationClusterRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation_cluster", - "type": "google.cloud.workstations_v1beta.types.WorkstationCluster" - }, - { - "name": "workstation_cluster_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_workstation_cluster" - }, - "description": "Sample for CreateWorkstationCluster", - "file": "workstations_v1beta_generated_workstations_create_workstation_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstationCluster_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": "workstations_v1beta_generated_workstations_create_workstation_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.create_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.CreateWorkstationClusterRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation_cluster", - "type": "google.cloud.workstations_v1beta.types.WorkstationCluster" - }, - { - "name": "workstation_cluster_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_workstation_cluster" - }, - "description": "Sample for CreateWorkstationCluster", - "file": "workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstationCluster_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": "workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.create_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.CreateWorkstationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation_config", - "type": "google.cloud.workstations_v1beta.types.WorkstationConfig" - }, - { - "name": "workstation_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_workstation_config" - }, - "description": "Sample for CreateWorkstationConfig", - "file": "workstations_v1beta_generated_workstations_create_workstation_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstationConfig_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": "workstations_v1beta_generated_workstations_create_workstation_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.create_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.CreateWorkstationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation_config", - "type": "google.cloud.workstations_v1beta.types.WorkstationConfig" - }, - { - "name": "workstation_config_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_workstation_config" - }, - "description": "Sample for CreateWorkstationConfig", - "file": "workstations_v1beta_generated_workstations_create_workstation_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstationConfig_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": "workstations_v1beta_generated_workstations_create_workstation_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.create_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.CreateWorkstationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation", - "type": "google.cloud.workstations_v1beta.types.Workstation" - }, - { - "name": "workstation_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_workstation" - }, - "description": "Sample for CreateWorkstation", - "file": "workstations_v1beta_generated_workstations_create_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstation_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": "workstations_v1beta_generated_workstations_create_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.create_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.CreateWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "CreateWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.CreateWorkstationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "workstation", - "type": "google.cloud.workstations_v1beta.types.Workstation" - }, - { - "name": "workstation_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_workstation" - }, - "description": "Sample for CreateWorkstation", - "file": "workstations_v1beta_generated_workstations_create_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_CreateWorkstation_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": "workstations_v1beta_generated_workstations_create_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.delete_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationClusterRequest" - }, - { - "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_workstation_cluster" - }, - "description": "Sample for DeleteWorkstationCluster", - "file": "workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_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": "workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.delete_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationClusterRequest" - }, - { - "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_workstation_cluster" - }, - "description": "Sample for DeleteWorkstationCluster", - "file": "workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_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": "workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.delete_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationConfigRequest" - }, - { - "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_workstation_config" - }, - "description": "Sample for DeleteWorkstationConfig", - "file": "workstations_v1beta_generated_workstations_delete_workstation_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_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": "workstations_v1beta_generated_workstations_delete_workstation_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.delete_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationConfigRequest" - }, - { - "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_workstation_config" - }, - "description": "Sample for DeleteWorkstationConfig", - "file": "workstations_v1beta_generated_workstations_delete_workstation_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_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": "workstations_v1beta_generated_workstations_delete_workstation_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.delete_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationRequest" - }, - { - "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_workstation" - }, - "description": "Sample for DeleteWorkstation", - "file": "workstations_v1beta_generated_workstations_delete_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstation_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": "workstations_v1beta_generated_workstations_delete_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.delete_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.DeleteWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "DeleteWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.DeleteWorkstationRequest" - }, - { - "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_workstation" - }, - "description": "Sample for DeleteWorkstation", - "file": "workstations_v1beta_generated_workstations_delete_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_DeleteWorkstation_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": "workstations_v1beta_generated_workstations_delete_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.generate_access_token", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.GenerateAccessToken", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "GenerateAccessToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.GenerateAccessTokenRequest" - }, - { - "name": "workstation", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.types.GenerateAccessTokenResponse", - "shortName": "generate_access_token" - }, - "description": "Sample for GenerateAccessToken", - "file": "workstations_v1beta_generated_workstations_generate_access_token_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_GenerateAccessToken_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": "workstations_v1beta_generated_workstations_generate_access_token_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.generate_access_token", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.GenerateAccessToken", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "GenerateAccessToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.GenerateAccessTokenRequest" - }, - { - "name": "workstation", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.workstations_v1beta.types.GenerateAccessTokenResponse", - "shortName": "generate_access_token" - }, - "description": "Sample for GenerateAccessToken", - "file": "workstations_v1beta_generated_workstations_generate_access_token_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_GenerateAccessToken_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": "workstations_v1beta_generated_workstations_generate_access_token_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.get_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.GetWorkstationClusterRequest" - }, - { - "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.workstations_v1beta.types.WorkstationCluster", - "shortName": "get_workstation_cluster" - }, - "description": "Sample for GetWorkstationCluster", - "file": "workstations_v1beta_generated_workstations_get_workstation_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstationCluster_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": "workstations_v1beta_generated_workstations_get_workstation_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.get_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.GetWorkstationClusterRequest" - }, - { - "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.workstations_v1beta.types.WorkstationCluster", - "shortName": "get_workstation_cluster" - }, - "description": "Sample for GetWorkstationCluster", - "file": "workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstationCluster_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": "workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.get_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.GetWorkstationConfigRequest" - }, - { - "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.workstations_v1beta.types.WorkstationConfig", - "shortName": "get_workstation_config" - }, - "description": "Sample for GetWorkstationConfig", - "file": "workstations_v1beta_generated_workstations_get_workstation_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstationConfig_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": "workstations_v1beta_generated_workstations_get_workstation_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.get_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.GetWorkstationConfigRequest" - }, - { - "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.workstations_v1beta.types.WorkstationConfig", - "shortName": "get_workstation_config" - }, - "description": "Sample for GetWorkstationConfig", - "file": "workstations_v1beta_generated_workstations_get_workstation_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstationConfig_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": "workstations_v1beta_generated_workstations_get_workstation_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.get_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.GetWorkstationRequest" - }, - { - "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.workstations_v1beta.types.Workstation", - "shortName": "get_workstation" - }, - "description": "Sample for GetWorkstation", - "file": "workstations_v1beta_generated_workstations_get_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstation_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": "workstations_v1beta_generated_workstations_get_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.get_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.GetWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "GetWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.GetWorkstationRequest" - }, - { - "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.workstations_v1beta.types.Workstation", - "shortName": "get_workstation" - }, - "description": "Sample for GetWorkstation", - "file": "workstations_v1beta_generated_workstations_get_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_GetWorkstation_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": "workstations_v1beta_generated_workstations_get_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_usable_workstation_configs", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListUsableWorkstationConfigs", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListUsableWorkstationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest" - }, - { - "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.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationConfigsAsyncPager", - "shortName": "list_usable_workstation_configs" - }, - "description": "Sample for ListUsableWorkstationConfigs", - "file": "workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_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": "workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_usable_workstation_configs", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListUsableWorkstationConfigs", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListUsableWorkstationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListUsableWorkstationConfigsRequest" - }, - { - "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.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationConfigsPager", - "shortName": "list_usable_workstation_configs" - }, - "description": "Sample for ListUsableWorkstationConfigs", - "file": "workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_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": "workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_usable_workstations", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListUsableWorkstations", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListUsableWorkstations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest" - }, - { - "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.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationsAsyncPager", - "shortName": "list_usable_workstations" - }, - "description": "Sample for ListUsableWorkstations", - "file": "workstations_v1beta_generated_workstations_list_usable_workstations_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListUsableWorkstations_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": "workstations_v1beta_generated_workstations_list_usable_workstations_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_usable_workstations", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListUsableWorkstations", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListUsableWorkstations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListUsableWorkstationsRequest" - }, - { - "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.workstations_v1beta.services.workstations.pagers.ListUsableWorkstationsPager", - "shortName": "list_usable_workstations" - }, - "description": "Sample for ListUsableWorkstations", - "file": "workstations_v1beta_generated_workstations_list_usable_workstations_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListUsableWorkstations_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": "workstations_v1beta_generated_workstations_list_usable_workstations_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_workstation_clusters", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstationClusters", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstationClusters" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest" - }, - { - "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.workstations_v1beta.services.workstations.pagers.ListWorkstationClustersAsyncPager", - "shortName": "list_workstation_clusters" - }, - "description": "Sample for ListWorkstationClusters", - "file": "workstations_v1beta_generated_workstations_list_workstation_clusters_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstationClusters_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": "workstations_v1beta_generated_workstations_list_workstation_clusters_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_workstation_clusters", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstationClusters", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstationClusters" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListWorkstationClustersRequest" - }, - { - "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.workstations_v1beta.services.workstations.pagers.ListWorkstationClustersPager", - "shortName": "list_workstation_clusters" - }, - "description": "Sample for ListWorkstationClusters", - "file": "workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstationClusters_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": "workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_workstation_configs", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstationConfigs", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest" - }, - { - "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.workstations_v1beta.services.workstations.pagers.ListWorkstationConfigsAsyncPager", - "shortName": "list_workstation_configs" - }, - "description": "Sample for ListWorkstationConfigs", - "file": "workstations_v1beta_generated_workstations_list_workstation_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstationConfigs_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": "workstations_v1beta_generated_workstations_list_workstation_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_workstation_configs", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstationConfigs", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstationConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListWorkstationConfigsRequest" - }, - { - "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.workstations_v1beta.services.workstations.pagers.ListWorkstationConfigsPager", - "shortName": "list_workstation_configs" - }, - "description": "Sample for ListWorkstationConfigs", - "file": "workstations_v1beta_generated_workstations_list_workstation_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstationConfigs_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": "workstations_v1beta_generated_workstations_list_workstation_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.list_workstations", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstations", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListWorkstationsRequest" - }, - { - "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.workstations_v1beta.services.workstations.pagers.ListWorkstationsAsyncPager", - "shortName": "list_workstations" - }, - "description": "Sample for ListWorkstations", - "file": "workstations_v1beta_generated_workstations_list_workstations_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstations_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": "workstations_v1beta_generated_workstations_list_workstations_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.list_workstations", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.ListWorkstations", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "ListWorkstations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.ListWorkstationsRequest" - }, - { - "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.workstations_v1beta.services.workstations.pagers.ListWorkstationsPager", - "shortName": "list_workstations" - }, - "description": "Sample for ListWorkstations", - "file": "workstations_v1beta_generated_workstations_list_workstations_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_ListWorkstations_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": "workstations_v1beta_generated_workstations_list_workstations_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.start_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.StartWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "StartWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.StartWorkstationRequest" - }, - { - "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": "start_workstation" - }, - "description": "Sample for StartWorkstation", - "file": "workstations_v1beta_generated_workstations_start_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_StartWorkstation_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": "workstations_v1beta_generated_workstations_start_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.start_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.StartWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "StartWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.StartWorkstationRequest" - }, - { - "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": "start_workstation" - }, - "description": "Sample for StartWorkstation", - "file": "workstations_v1beta_generated_workstations_start_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_StartWorkstation_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": "workstations_v1beta_generated_workstations_start_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.stop_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.StopWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "StopWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.StopWorkstationRequest" - }, - { - "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": "stop_workstation" - }, - "description": "Sample for StopWorkstation", - "file": "workstations_v1beta_generated_workstations_stop_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_StopWorkstation_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": "workstations_v1beta_generated_workstations_stop_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.stop_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.StopWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "StopWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.StopWorkstationRequest" - }, - { - "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": "stop_workstation" - }, - "description": "Sample for StopWorkstation", - "file": "workstations_v1beta_generated_workstations_stop_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_StopWorkstation_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": "workstations_v1beta_generated_workstations_stop_workstation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.update_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationClusterRequest" - }, - { - "name": "workstation_cluster", - "type": "google.cloud.workstations_v1beta.types.WorkstationCluster" - }, - { - "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_workstation_cluster" - }, - "description": "Sample for UpdateWorkstationCluster", - "file": "workstations_v1beta_generated_workstations_update_workstation_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_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": "workstations_v1beta_generated_workstations_update_workstation_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.update_workstation_cluster", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstationCluster", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstationCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationClusterRequest" - }, - { - "name": "workstation_cluster", - "type": "google.cloud.workstations_v1beta.types.WorkstationCluster" - }, - { - "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_workstation_cluster" - }, - "description": "Sample for UpdateWorkstationCluster", - "file": "workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_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": "workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.update_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationConfigRequest" - }, - { - "name": "workstation_config", - "type": "google.cloud.workstations_v1beta.types.WorkstationConfig" - }, - { - "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_workstation_config" - }, - "description": "Sample for UpdateWorkstationConfig", - "file": "workstations_v1beta_generated_workstations_update_workstation_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_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": "workstations_v1beta_generated_workstations_update_workstation_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.update_workstation_config", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstationConfig", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstationConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationConfigRequest" - }, - { - "name": "workstation_config", - "type": "google.cloud.workstations_v1beta.types.WorkstationConfig" - }, - { - "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_workstation_config" - }, - "description": "Sample for UpdateWorkstationConfig", - "file": "workstations_v1beta_generated_workstations_update_workstation_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_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": "workstations_v1beta_generated_workstations_update_workstation_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient", - "shortName": "WorkstationsAsyncClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsAsyncClient.update_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationRequest" - }, - { - "name": "workstation", - "type": "google.cloud.workstations_v1beta.types.Workstation" - }, - { - "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_workstation" - }, - "description": "Sample for UpdateWorkstation", - "file": "workstations_v1beta_generated_workstations_update_workstation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstation_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": "workstations_v1beta_generated_workstations_update_workstation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient", - "shortName": "WorkstationsClient" - }, - "fullName": "google.cloud.workstations_v1beta.WorkstationsClient.update_workstation", - "method": { - "fullName": "google.cloud.workstations.v1beta.Workstations.UpdateWorkstation", - "service": { - "fullName": "google.cloud.workstations.v1beta.Workstations", - "shortName": "Workstations" - }, - "shortName": "UpdateWorkstation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.workstations_v1beta.types.UpdateWorkstationRequest" - }, - { - "name": "workstation", - "type": "google.cloud.workstations_v1beta.types.Workstation" - }, - { - "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_workstation" - }, - "description": "Sample for UpdateWorkstation", - "file": "workstations_v1beta_generated_workstations_update_workstation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "workstations_v1beta_generated_Workstations_UpdateWorkstation_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": "workstations_v1beta_generated_workstations_update_workstation_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_async.py deleted file mode 100644 index be67b4246ac4..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_CreateWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_create_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationRequest( - parent="parent_value", - workstation_id="workstation_id_value", - ) - - # Make the request - operation = client.create_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_CreateWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_async.py deleted file mode 100644 index 9b136279f21a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_CreateWorkstationCluster_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_create_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationClusterRequest( - parent="parent_value", - workstation_cluster_id="workstation_cluster_id_value", - ) - - # Make the request - operation = client.create_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_CreateWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py deleted file mode 100644 index fcf1bcea66d1..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_cluster_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_CreateWorkstationCluster_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_create_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationClusterRequest( - parent="parent_value", - workstation_cluster_id="workstation_cluster_id_value", - ) - - # Make the request - operation = client.create_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_CreateWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_async.py deleted file mode 100644 index 7be0818eccb4..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_CreateWorkstationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_create_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationConfigRequest( - parent="parent_value", - workstation_config_id="workstation_config_id_value", - ) - - # Make the request - operation = client.create_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_CreateWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_sync.py deleted file mode 100644 index bdf2496d486c..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_config_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_CreateWorkstationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_create_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationConfigRequest( - parent="parent_value", - workstation_config_id="workstation_config_id_value", - ) - - # Make the request - operation = client.create_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_CreateWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_sync.py deleted file mode 100644 index b841bfbb8d8d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_create_workstation_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_CreateWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_create_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.CreateWorkstationRequest( - parent="parent_value", - workstation_id="workstation_id_value", - ) - - # Make the request - operation = client.create_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_CreateWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_async.py deleted file mode 100644 index 6f544d0f9324..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_DeleteWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_delete_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_DeleteWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py deleted file mode 100644 index 4ca8290db920..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_delete_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py deleted file mode 100644 index d8b839644d89..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_cluster_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_delete_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_DeleteWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_async.py deleted file mode 100644 index 6124931d5494..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_delete_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_sync.py deleted file mode 100644 index 1fa571dd19ca..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_config_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_delete_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_DeleteWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_sync.py deleted file mode 100644 index c472ff766271..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_delete_workstation_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_DeleteWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_delete_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.DeleteWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_DeleteWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_async.py deleted file mode 100644 index c48ea1e2bafd..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateAccessToken -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_GenerateAccessToken_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_generate_access_token(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.GenerateAccessTokenRequest( - workstation="workstation_value", - ) - - # Make the request - response = await client.generate_access_token(request=request) - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_GenerateAccessToken_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_sync.py deleted file mode 100644 index 263cb465e60a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_generate_access_token_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateAccessToken -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_GenerateAccessToken_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_generate_access_token(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.GenerateAccessTokenRequest( - workstation="workstation_value", - ) - - # Make the request - response = client.generate_access_token(request=request) - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_GenerateAccessToken_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_async.py deleted file mode 100644 index 06b3380ee695..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_GetWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_get_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation(request=request) - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_GetWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_async.py deleted file mode 100644 index 33706220659e..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_GetWorkstationCluster_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_get_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation_cluster(request=request) - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_GetWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py deleted file mode 100644 index 0eaa770a84e4..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_cluster_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_GetWorkstationCluster_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_get_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationClusterRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation_cluster(request=request) - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_GetWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_async.py deleted file mode 100644 index 3826622fc27d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_GetWorkstationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_get_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_workstation_config(request=request) - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_GetWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_sync.py deleted file mode 100644 index 3b2378263be8..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_config_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_GetWorkstationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_get_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation_config(request=request) - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_GetWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_sync.py deleted file mode 100644 index 8f2387aa7d5a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_get_workstation_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_GetWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_get_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.GetWorkstationRequest( - name="name_value", - ) - - # Make the request - response = client.get_workstation(request=request) - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_GetWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py deleted file mode 100644 index 85349489cc32..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListUsableWorkstationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_list_usable_workstation_configs(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListUsableWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstation_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py deleted file mode 100644 index 1d5253a514e9..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstation_configs_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListUsableWorkstationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_list_usable_workstation_configs(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListUsableWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstation_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListUsableWorkstationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_async.py deleted file mode 100644 index c3a757c5ca1d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListUsableWorkstations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListUsableWorkstations_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_list_usable_workstations(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListUsableWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstations(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListUsableWorkstations_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_sync.py deleted file mode 100644 index d93a51c1ae18..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_usable_workstations_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListUsableWorkstations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListUsableWorkstations_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_list_usable_workstations(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListUsableWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_usable_workstations(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListUsableWorkstations_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_async.py deleted file mode 100644 index 99c25e91565c..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListWorkstationClusters -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListWorkstationClusters_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_list_workstation_clusters(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_clusters(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListWorkstationClusters_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py deleted file mode 100644 index 977a14ef9606..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_clusters_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListWorkstationClusters -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListWorkstationClusters_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_list_workstation_clusters(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_clusters(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListWorkstationClusters_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_async.py deleted file mode 100644 index 6cf8fd8e387d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListWorkstationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListWorkstationConfigs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_list_workstation_configs(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListWorkstationConfigs_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_sync.py deleted file mode 100644 index 3a2b40396cde..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstation_configs_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListWorkstationConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListWorkstationConfigs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_list_workstation_configs(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationConfigsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstation_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListWorkstationConfigs_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_async.py deleted file mode 100644 index 344f96f8712e..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListWorkstations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListWorkstations_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_list_workstations(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstations(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListWorkstations_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_sync.py deleted file mode 100644 index 94220467c51d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_list_workstations_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListWorkstations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_ListWorkstations_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_list_workstations(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.ListWorkstationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workstations(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END workstations_v1beta_generated_Workstations_ListWorkstations_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_async.py deleted file mode 100644 index 8b2a6fae61a3..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StartWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_StartWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_start_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.StartWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.start_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_StartWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_sync.py deleted file mode 100644 index 2cc02373acf6..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_start_workstation_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StartWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_StartWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_start_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.StartWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.start_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_StartWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_async.py deleted file mode 100644 index 34af46912505..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StopWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_StopWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_stop_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.StopWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.stop_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_StopWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_sync.py deleted file mode 100644 index 023274feb4e4..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_stop_workstation_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StopWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_StopWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_stop_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.StopWorkstationRequest( - name="name_value", - ) - - # Make the request - operation = client.stop_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_StopWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_async.py deleted file mode 100644 index 7c475a71fae9..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_UpdateWorkstation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_update_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationRequest( - ) - - # Make the request - operation = client.update_workstation(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_UpdateWorkstation_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_async.py deleted file mode 100644 index 89b200ae4115..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_update_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationClusterRequest( - ) - - # Make the request - operation = client.update_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py deleted file mode 100644 index 2f431bd63d3f..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_cluster_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateWorkstationCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_update_workstation_cluster(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationClusterRequest( - ) - - # Make the request - operation = client.update_workstation_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_UpdateWorkstationCluster_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_async.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_async.py deleted file mode 100644 index 2ca5c4c80b0a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -async def sample_update_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsAsyncClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationConfigRequest( - ) - - # Make the request - operation = client.update_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_async] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_sync.py deleted file mode 100644 index c6080dd0951c..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_config_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateWorkstationConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_update_workstation_config(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationConfigRequest( - ) - - # Make the request - operation = client.update_workstation_config(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_UpdateWorkstationConfig_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_sync.py b/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_sync.py deleted file mode 100644 index 450b03b0fb44..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/samples/generated_samples/workstations_v1beta_generated_workstations_update_workstation_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateWorkstation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-workstations - - -# [START workstations_v1beta_generated_Workstations_UpdateWorkstation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import workstations_v1beta - - -def sample_update_workstation(): - # Create a client - client = workstations_v1beta.WorkstationsClient() - - # Initialize request argument(s) - request = workstations_v1beta.UpdateWorkstationRequest( - ) - - # Make the request - operation = client.update_workstation(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END workstations_v1beta_generated_Workstations_UpdateWorkstation_sync] diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/scripts/fixup_workstations_v1beta_keywords.py b/owl-bot-staging/google-cloud-workstations/v1beta/scripts/fixup_workstations_v1beta_keywords.py deleted file mode 100644 index 4f7ba7cb1e17..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/scripts/fixup_workstations_v1beta_keywords.py +++ /dev/null @@ -1,195 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 workstationsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_workstation': ('parent', 'workstation_id', 'workstation', 'validate_only', ), - 'create_workstation_cluster': ('parent', 'workstation_cluster_id', 'workstation_cluster', 'validate_only', ), - 'create_workstation_config': ('parent', 'workstation_config_id', 'workstation_config', 'validate_only', ), - 'delete_workstation': ('name', 'validate_only', 'etag', ), - 'delete_workstation_cluster': ('name', 'validate_only', 'etag', 'force', ), - 'delete_workstation_config': ('name', 'validate_only', 'etag', 'force', ), - 'generate_access_token': ('workstation', 'expire_time', 'ttl', ), - 'get_workstation': ('name', ), - 'get_workstation_cluster': ('name', ), - 'get_workstation_config': ('name', ), - 'list_usable_workstation_configs': ('parent', 'page_size', 'page_token', ), - 'list_usable_workstations': ('parent', 'page_size', 'page_token', ), - 'list_workstation_clusters': ('parent', 'page_size', 'page_token', ), - 'list_workstation_configs': ('parent', 'page_size', 'page_token', ), - 'list_workstations': ('parent', 'page_size', 'page_token', ), - 'start_workstation': ('name', 'validate_only', 'etag', ), - 'stop_workstation': ('name', 'validate_only', 'etag', ), - 'update_workstation': ('workstation', 'update_mask', 'validate_only', 'allow_missing', ), - 'update_workstation_cluster': ('workstation_cluster', 'update_mask', 'validate_only', 'allow_missing', ), - 'update_workstation_config': ('workstation_config', 'update_mask', 'validate_only', 'allow_missing', ), - } - - 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=workstationsCallTransformer(), -): - """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 workstations client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/setup.py b/owl-bot-staging/google-cloud-workstations/v1beta/setup.py deleted file mode 100644 index 1483952d60ff..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/setup.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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-workstations' - - -description = "Google Cloud Workstations API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/workstations/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-workstations" - -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/google-cloud-workstations/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.7.txt deleted file mode 100644 index 2beecf99e0be..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/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/google-cloud-workstations/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/tests/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/__init__.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/test_workstations.py b/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/test_workstations.py deleted file mode 100644 index a60ab176597a..000000000000 --- a/owl-bot-staging/google-cloud-workstations/v1beta/tests/unit/gapic/workstations_v1beta/test_workstations.py +++ /dev/null @@ -1,13504 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.location import locations_pb2 -from google.cloud.workstations_v1beta.services.workstations import WorkstationsAsyncClient -from google.cloud.workstations_v1beta.services.workstations import WorkstationsClient -from google.cloud.workstations_v1beta.services.workstations import pagers -from google.cloud.workstations_v1beta.services.workstations import transports -from google.cloud.workstations_v1beta.types import workstations -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 any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_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 WorkstationsClient._get_default_mtls_endpoint(None) is None - assert WorkstationsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert WorkstationsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert WorkstationsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert WorkstationsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert WorkstationsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (WorkstationsClient, "grpc"), - (WorkstationsAsyncClient, "grpc_asyncio"), - (WorkstationsClient, "rest"), -]) -def test_workstations_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 == ( - 'workstations.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://workstations.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.WorkstationsGrpcTransport, "grpc"), - (transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.WorkstationsRestTransport, "rest"), -]) -def test_workstations_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", [ - (WorkstationsClient, "grpc"), - (WorkstationsAsyncClient, "grpc_asyncio"), - (WorkstationsClient, "rest"), -]) -def test_workstations_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 == ( - 'workstations.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://workstations.googleapis.com' - ) - - -def test_workstations_client_get_transport_class(): - transport = WorkstationsClient.get_transport_class() - available_transports = [ - transports.WorkstationsGrpcTransport, - transports.WorkstationsRestTransport, - ] - assert transport in available_transports - - transport = WorkstationsClient.get_transport_class("grpc") - assert transport == transports.WorkstationsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), -]) -@mock.patch.object(WorkstationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsClient)) -@mock.patch.object(WorkstationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsAsyncClient)) -def test_workstations_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(WorkstationsClient, '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(WorkstationsClient, '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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", "true"), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", "false"), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest", "true"), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest", "false"), -]) -@mock.patch.object(WorkstationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsClient)) -@mock.patch.object(WorkstationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_workstations_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", [ - WorkstationsClient, WorkstationsAsyncClient -]) -@mock.patch.object(WorkstationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsClient)) -@mock.patch.object(WorkstationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WorkstationsAsyncClient)) -def test_workstations_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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc"), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio"), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest"), -]) -def test_workstations_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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", grpc_helpers), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (WorkstationsClient, transports.WorkstationsRestTransport, "rest", None), -]) -def test_workstations_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_workstations_client_client_options_from_dict(): - with mock.patch('google.cloud.workstations_v1beta.services.workstations.transports.WorkstationsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = WorkstationsClient( - 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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport, "grpc", grpc_helpers), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_workstations_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( - "workstations.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="workstations.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationClusterRequest, - dict, -]) -def test_get_workstation_cluster(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationCluster( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - network='network_value', - subnetwork='subnetwork_value', - control_plane_ip='control_plane_ip_value', - degraded=True, - ) - response = client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationClusterRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationCluster) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.network == 'network_value' - assert response.subnetwork == 'subnetwork_value' - assert response.control_plane_ip == 'control_plane_ip_value' - assert response.degraded is True - - -def test_get_workstation_cluster_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_cluster), - '__call__') as call: - client.get_workstation_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationClusterRequest() - -@pytest.mark.asyncio -async def test_get_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationClusterRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - network='network_value', - subnetwork='subnetwork_value', - control_plane_ip='control_plane_ip_value', - degraded=True, - )) - response = await client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationClusterRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationCluster) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.network == 'network_value' - assert response.subnetwork == 'subnetwork_value' - assert response.control_plane_ip == 'control_plane_ip_value' - assert response.degraded is True - - -@pytest.mark.asyncio -async def test_get_workstation_cluster_async_from_dict(): - await test_get_workstation_cluster_async(request_type=dict) - - -def test_get_workstation_cluster_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - call.return_value = workstations.WorkstationCluster() - client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster()) - await client.get_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationCluster() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_workstation_cluster( - 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_workstation_cluster_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_cluster( - workstations.GetWorkstationClusterRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_workstation_cluster_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationCluster() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationCluster()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_workstation_cluster( - 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_workstation_cluster_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_cluster( - workstations.GetWorkstationClusterRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationClustersRequest, - dict, -]) -def test_list_workstation_clusters(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationClustersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationClustersRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationClustersPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workstation_clusters_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_clusters), - '__call__') as call: - client.list_workstation_clusters() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationClustersRequest() - -@pytest.mark.asyncio -async def test_list_workstation_clusters_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationClustersRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationClustersRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationClustersAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_workstation_clusters_async_from_dict(): - await test_list_workstation_clusters_async(request_type=dict) - - -def test_list_workstation_clusters_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationClustersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - call.return_value = workstations.ListWorkstationClustersResponse() - client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_workstation_clusters_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationClustersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse()) - await client.list_workstation_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_workstation_clusters_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationClustersResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_workstation_clusters( - 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_workstation_clusters_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_clusters( - workstations.ListWorkstationClustersRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_workstation_clusters_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationClustersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationClustersResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_workstation_clusters( - 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_workstation_clusters_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_clusters( - workstations.ListWorkstationClustersRequest(), - parent='parent_value', - ) - - -def test_list_workstation_clusters_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstation_clusters), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_workstation_clusters(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.WorkstationCluster) - for i in results) -def test_list_workstation_clusters_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstation_clusters), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - RuntimeError, - ) - pages = list(client.list_workstation_clusters(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_workstation_clusters_async_pager(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_workstation_clusters(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, workstations.WorkstationCluster) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_workstation_clusters_async_pages(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_clusters), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_workstation_clusters(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - workstations.CreateWorkstationClusterRequest, - dict, -]) -def test_create_workstation_cluster(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationClusterRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_workstation_cluster_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_cluster), - '__call__') as call: - client.create_workstation_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationClusterRequest() - -@pytest.mark.asyncio -async def test_create_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationClusterRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__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_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationClusterRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_workstation_cluster_async_from_dict(): - await test_create_workstation_cluster_async(request_type=dict) - - -def test_create_workstation_cluster_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationClusterRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_workstation_cluster_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationClusterRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_workstation_cluster_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__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_workstation_cluster( - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].workstation_cluster - mock_val = workstations.WorkstationCluster(name='name_value') - assert arg == mock_val - arg = args[0].workstation_cluster_id - mock_val = 'workstation_cluster_id_value' - assert arg == mock_val - - -def test_create_workstation_cluster_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_cluster( - workstations.CreateWorkstationClusterRequest(), - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_value', - ) - -@pytest.mark.asyncio -async def test_create_workstation_cluster_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_cluster), - '__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_workstation_cluster( - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].workstation_cluster - mock_val = workstations.WorkstationCluster(name='name_value') - assert arg == mock_val - arg = args[0].workstation_cluster_id - mock_val = 'workstation_cluster_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_workstation_cluster_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_cluster( - workstations.CreateWorkstationClusterRequest(), - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationClusterRequest, - dict, -]) -def test_update_workstation_cluster(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationClusterRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_workstation_cluster_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_cluster), - '__call__') as call: - client.update_workstation_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationClusterRequest() - -@pytest.mark.asyncio -async def test_update_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationClusterRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__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_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationClusterRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_workstation_cluster_async_from_dict(): - await test_update_workstation_cluster_async(request_type=dict) - - -def test_update_workstation_cluster_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationClusterRequest() - - request.workstation_cluster.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation_cluster.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_workstation_cluster_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationClusterRequest() - - request.workstation_cluster.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation_cluster.name=name_value', - ) in kw['metadata'] - - -def test_update_workstation_cluster_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__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_workstation_cluster( - workstation_cluster=workstations.WorkstationCluster(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].workstation_cluster - mock_val = workstations.WorkstationCluster(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_workstation_cluster_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_cluster( - workstations.UpdateWorkstationClusterRequest(), - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_workstation_cluster_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_cluster), - '__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_workstation_cluster( - workstation_cluster=workstations.WorkstationCluster(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].workstation_cluster - mock_val = workstations.WorkstationCluster(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_workstation_cluster_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_cluster( - workstations.UpdateWorkstationClusterRequest(), - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationClusterRequest, - dict, -]) -def test_delete_workstation_cluster(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationClusterRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_workstation_cluster_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_cluster), - '__call__') as call: - client.delete_workstation_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationClusterRequest() - -@pytest.mark.asyncio -async def test_delete_workstation_cluster_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationClusterRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_cluster), - '__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_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationClusterRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_workstation_cluster_async_from_dict(): - await test_delete_workstation_cluster_async(request_type=dict) - - -def test_delete_workstation_cluster_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_workstation_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_cluster_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__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_workstation_cluster( - 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_workstation_cluster_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_cluster( - workstations.DeleteWorkstationClusterRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_workstation_cluster_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_cluster), - '__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_workstation_cluster( - 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_workstation_cluster_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_cluster( - workstations.DeleteWorkstationClusterRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationConfigRequest, - dict, -]) -def test_get_workstation_config(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationConfig( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - degraded=True, - enable_audit_agent=True, - ) - response = client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.degraded is True - assert response.enable_audit_agent is True - - -def test_get_workstation_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_config), - '__call__') as call: - client.get_workstation_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationConfigRequest() - -@pytest.mark.asyncio -async def test_get_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationConfigRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - degraded=True, - enable_audit_agent=True, - )) - response = await client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.degraded is True - assert response.enable_audit_agent is True - - -@pytest.mark.asyncio -async def test_get_workstation_config_async_from_dict(): - await test_get_workstation_config_async(request_type=dict) - - -def test_get_workstation_config_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - call.return_value = workstations.WorkstationConfig() - client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_workstation_config_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig()) - await client.get_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_workstation_config_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_workstation_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_workstation_config_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_config( - workstations.GetWorkstationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_workstation_config_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.WorkstationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.WorkstationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_workstation_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_workstation_config_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_config( - workstations.GetWorkstationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationConfigsRequest, - dict, -]) -def test_list_workstation_configs(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workstation_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_configs), - '__call__') as call: - client.list_workstation_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationConfigsRequest() - -@pytest.mark.asyncio -async def test_list_workstation_configs_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationConfigsRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_workstation_configs_async_from_dict(): - await test_list_workstation_configs_async(request_type=dict) - - -def test_list_workstation_configs_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - call.return_value = workstations.ListWorkstationConfigsResponse() - client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_workstation_configs_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse()) - await client.list_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_workstation_configs_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_workstation_configs( - 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_workstation_configs_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_configs( - workstations.ListWorkstationConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_workstation_configs_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_workstation_configs( - 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_workstation_configs_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_configs( - workstations.ListWorkstationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_workstation_configs_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstation_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_workstation_configs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.WorkstationConfig) - for i in results) -def test_list_workstation_configs_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstation_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_workstation_configs(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_workstation_configs_async_pager(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_workstation_configs(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, workstations.WorkstationConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_workstation_configs_async_pages(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstation_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_workstation_configs(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - workstations.ListUsableWorkstationConfigsRequest, - dict, -]) -def test_list_usable_workstation_configs(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_usable_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListUsableWorkstationConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_usable_workstation_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_usable_workstation_configs), - '__call__') as call: - client.list_usable_workstation_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListUsableWorkstationConfigsRequest() - -@pytest.mark.asyncio -async def test_list_usable_workstation_configs_async(transport: str = 'grpc_asyncio', request_type=workstations.ListUsableWorkstationConfigsRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_usable_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListUsableWorkstationConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_usable_workstation_configs_async_from_dict(): - await test_list_usable_workstation_configs_async(request_type=dict) - - -def test_list_usable_workstation_configs_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListUsableWorkstationConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - call.return_value = workstations.ListUsableWorkstationConfigsResponse() - client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_usable_workstation_configs_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListUsableWorkstationConfigsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse()) - await client.list_usable_workstation_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_usable_workstation_configs_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_usable_workstation_configs( - 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_usable_workstation_configs_flattened_error(): - client = WorkstationsClient( - credentials=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_usable_workstation_configs( - workstations.ListUsableWorkstationConfigsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_usable_workstation_configs_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_usable_workstation_configs( - 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_usable_workstation_configs_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_usable_workstation_configs( - workstations.ListUsableWorkstationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_usable_workstation_configs_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_usable_workstation_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_usable_workstation_configs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.WorkstationConfig) - for i in results) -def test_list_usable_workstation_configs_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_usable_workstation_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_usable_workstation_configs(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_usable_workstation_configs_async_pager(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_usable_workstation_configs(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, workstations.WorkstationConfig) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_usable_workstation_configs_async_pages(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstation_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_usable_workstation_configs(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - workstations.CreateWorkstationConfigRequest, - dict, -]) -def test_create_workstation_config(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_workstation_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_config), - '__call__') as call: - client.create_workstation_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationConfigRequest() - -@pytest.mark.asyncio -async def test_create_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationConfigRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__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_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_workstation_config_async_from_dict(): - await test_create_workstation_config_async(request_type=dict) - - -def test_create_workstation_config_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_workstation_config_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_workstation_config_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__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_workstation_config( - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].workstation_config - mock_val = workstations.WorkstationConfig(name='name_value') - assert arg == mock_val - arg = args[0].workstation_config_id - mock_val = 'workstation_config_id_value' - assert arg == mock_val - - -def test_create_workstation_config_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_config( - workstations.CreateWorkstationConfigRequest(), - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_value', - ) - -@pytest.mark.asyncio -async def test_create_workstation_config_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation_config), - '__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_workstation_config( - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].workstation_config - mock_val = workstations.WorkstationConfig(name='name_value') - assert arg == mock_val - arg = args[0].workstation_config_id - mock_val = 'workstation_config_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_workstation_config_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_config( - workstations.CreateWorkstationConfigRequest(), - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationConfigRequest, - dict, -]) -def test_update_workstation_config(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_workstation_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_config), - '__call__') as call: - client.update_workstation_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationConfigRequest() - -@pytest.mark.asyncio -async def test_update_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationConfigRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__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_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_workstation_config_async_from_dict(): - await test_update_workstation_config_async(request_type=dict) - - -def test_update_workstation_config_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationConfigRequest() - - request.workstation_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_workstation_config_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationConfigRequest() - - request.workstation_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation_config.name=name_value', - ) in kw['metadata'] - - -def test_update_workstation_config_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__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_workstation_config( - workstation_config=workstations.WorkstationConfig(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].workstation_config - mock_val = workstations.WorkstationConfig(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_workstation_config_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_config( - workstations.UpdateWorkstationConfigRequest(), - workstation_config=workstations.WorkstationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_workstation_config_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation_config), - '__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_workstation_config( - workstation_config=workstations.WorkstationConfig(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].workstation_config - mock_val = workstations.WorkstationConfig(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_workstation_config_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_config( - workstations.UpdateWorkstationConfigRequest(), - workstation_config=workstations.WorkstationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationConfigRequest, - dict, -]) -def test_delete_workstation_config(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_workstation_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation_config), - '__call__') as call: - client.delete_workstation_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationConfigRequest() - -@pytest.mark.asyncio -async def test_delete_workstation_config_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationConfigRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation_config), - '__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_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_workstation_config_async_from_dict(): - await test_delete_workstation_config_async(request_type=dict) - - -def test_delete_workstation_config_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_workstation_config_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_workstation_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_workstation_config_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__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_workstation_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_workstation_config_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation_config( - workstations.DeleteWorkstationConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_workstation_config_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation_config), - '__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_workstation_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_workstation_config_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation_config( - workstations.DeleteWorkstationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationRequest, - dict, -]) -def test_get_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.Workstation( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - state=workstations.Workstation.State.STATE_STARTING, - host='host_value', - ) - response = client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.Workstation) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.state == workstations.Workstation.State.STATE_STARTING - assert response.host == 'host_value' - - -def test_get_workstation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation), - '__call__') as call: - client.get_workstation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationRequest() - -@pytest.mark.asyncio -async def test_get_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.GetWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - state=workstations.Workstation.State.STATE_STARTING, - host='host_value', - )) - response = await client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GetWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.Workstation) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.state == workstations.Workstation.State.STATE_STARTING - assert response.host == 'host_value' - - -@pytest.mark.asyncio -async def test_get_workstation_async_from_dict(): - await test_get_workstation_async(request_type=dict) - - -def test_get_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - call.return_value = workstations.Workstation() - client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GetWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation()) - await client.get_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.Workstation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_workstation( - 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_workstation_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation( - workstations.GetWorkstationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.Workstation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.Workstation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_workstation( - 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_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation( - workstations.GetWorkstationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationsRequest, - dict, -]) -def test_list_workstations(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workstations_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstations), - '__call__') as call: - client.list_workstations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationsRequest() - -@pytest.mark.asyncio -async def test_list_workstations_async(transport: str = 'grpc_asyncio', request_type=workstations.ListWorkstationsRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListWorkstationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_workstations_async_from_dict(): - await test_list_workstations_async(request_type=dict) - - -def test_list_workstations_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - call.return_value = workstations.ListWorkstationsResponse() - client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_workstations_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListWorkstationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse()) - await client.list_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_workstations_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_workstations( - 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_workstations_flattened_error(): - client = WorkstationsClient( - credentials=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_workstations( - workstations.ListWorkstationsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_workstations_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListWorkstationsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListWorkstationsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_workstations( - 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_workstations_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstations( - workstations.ListWorkstationsRequest(), - parent='parent_value', - ) - - -def test_list_workstations_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_workstations(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.Workstation) - for i in results) -def test_list_workstations_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_workstations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - pages = list(client.list_workstations(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_workstations_async_pager(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_workstations(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, workstations.Workstation) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_workstations_async_pages(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workstations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_workstations(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - workstations.ListUsableWorkstationsRequest, - dict, -]) -def test_list_usable_workstations(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_usable_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListUsableWorkstationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_usable_workstations_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_usable_workstations), - '__call__') as call: - client.list_usable_workstations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListUsableWorkstationsRequest() - -@pytest.mark.asyncio -async def test_list_usable_workstations_async(transport: str = 'grpc_asyncio', request_type=workstations.ListUsableWorkstationsRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_usable_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.ListUsableWorkstationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_usable_workstations_async_from_dict(): - await test_list_usable_workstations_async(request_type=dict) - - -def test_list_usable_workstations_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListUsableWorkstationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - call.return_value = workstations.ListUsableWorkstationsResponse() - client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_usable_workstations_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.ListUsableWorkstationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse()) - await client.list_usable_workstations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_usable_workstations_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_usable_workstations( - 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_usable_workstations_flattened_error(): - client = WorkstationsClient( - credentials=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_usable_workstations( - workstations.ListUsableWorkstationsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_usable_workstations_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.ListUsableWorkstationsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.ListUsableWorkstationsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_usable_workstations( - 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_usable_workstations_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_usable_workstations( - workstations.ListUsableWorkstationsRequest(), - parent='parent_value', - ) - - -def test_list_usable_workstations_pager(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_usable_workstations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_usable_workstations(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.Workstation) - for i in results) -def test_list_usable_workstations_pages(transport_name: str = "grpc"): - client = WorkstationsClient( - 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_usable_workstations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - pages = list(client.list_usable_workstations(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_usable_workstations_async_pager(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_usable_workstations(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, workstations.Workstation) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_usable_workstations_async_pages(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_usable_workstations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_usable_workstations(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - workstations.CreateWorkstationRequest, - dict, -]) -def test_create_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_workstation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation), - '__call__') as call: - client.create_workstation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationRequest() - -@pytest.mark.asyncio -async def test_create_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.CreateWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__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_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.CreateWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_workstation_async_from_dict(): - await test_create_workstation_async(request_type=dict) - - -def test_create_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.CreateWorkstationRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__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_workstation( - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].workstation - mock_val = workstations.Workstation(name='name_value') - assert arg == mock_val - arg = args[0].workstation_id - mock_val = 'workstation_id_value' - assert arg == mock_val - - -def test_create_workstation_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation( - workstations.CreateWorkstationRequest(), - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_value', - ) - -@pytest.mark.asyncio -async def test_create_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_workstation), - '__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_workstation( - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].workstation - mock_val = workstations.Workstation(name='name_value') - assert arg == mock_val - arg = args[0].workstation_id - mock_val = 'workstation_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation( - workstations.CreateWorkstationRequest(), - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationRequest, - dict, -]) -def test_update_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_workstation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation), - '__call__') as call: - client.update_workstation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationRequest() - -@pytest.mark.asyncio -async def test_update_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.UpdateWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__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_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.UpdateWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_workstation_async_from_dict(): - await test_update_workstation_async(request_type=dict) - - -def test_update_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationRequest() - - request.workstation.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.UpdateWorkstationRequest() - - request.workstation.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation.name=name_value', - ) in kw['metadata'] - - -def test_update_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__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_workstation( - workstation=workstations.Workstation(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].workstation - mock_val = workstations.Workstation(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_workstation_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation( - workstations.UpdateWorkstationRequest(), - workstation=workstations.Workstation(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_workstation), - '__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_workstation( - workstation=workstations.Workstation(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].workstation - mock_val = workstations.Workstation(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_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation( - workstations.UpdateWorkstationRequest(), - workstation=workstations.Workstation(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationRequest, - dict, -]) -def test_delete_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_workstation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=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_workstation), - '__call__') as call: - client.delete_workstation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationRequest() - -@pytest.mark.asyncio -async def test_delete_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.DeleteWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_workstation), - '__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_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.DeleteWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_workstation_async_from_dict(): - await test_delete_workstation_async(request_type=dict) - - -def test_delete_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.DeleteWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__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_workstation( - 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_workstation_flattened_error(): - client = WorkstationsClient( - credentials=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_workstation( - workstations.DeleteWorkstationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_workstation), - '__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_workstation( - 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_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - 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_workstation( - workstations.DeleteWorkstationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.StartWorkstationRequest, - dict, -]) -def test_start_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.start_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.StartWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_start_workstation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - client.start_workstation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.StartWorkstationRequest() - -@pytest.mark.asyncio -async def test_start_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.StartWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__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.start_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.StartWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_start_workstation_async_from_dict(): - await test_start_workstation_async(request_type=dict) - - -def test_start_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.StartWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.start_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_start_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.StartWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.start_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_start_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__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.start_workstation( - 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_start_workstation_flattened_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.start_workstation( - workstations.StartWorkstationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_start_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_workstation), - '__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.start_workstation( - 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_start_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - 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.start_workstation( - workstations.StartWorkstationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.StopWorkstationRequest, - dict, -]) -def test_stop_workstation(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.stop_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.StopWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_stop_workstation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - client.stop_workstation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.StopWorkstationRequest() - -@pytest.mark.asyncio -async def test_stop_workstation_async(transport: str = 'grpc_asyncio', request_type=workstations.StopWorkstationRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__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.stop_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.StopWorkstationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_stop_workstation_async_from_dict(): - await test_stop_workstation_async(request_type=dict) - - -def test_stop_workstation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.StopWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.stop_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_stop_workstation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.StopWorkstationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.stop_workstation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_stop_workstation_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__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.stop_workstation( - 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_stop_workstation_flattened_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.stop_workstation( - workstations.StopWorkstationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_stop_workstation_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_workstation), - '__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.stop_workstation( - 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_stop_workstation_flattened_error_async(): - client = WorkstationsAsyncClient( - 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.stop_workstation( - workstations.StopWorkstationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GenerateAccessTokenRequest, - dict, -]) -def test_generate_access_token(request_type, transport: str = 'grpc'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.GenerateAccessTokenResponse( - access_token='access_token_value', - ) - response = client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GenerateAccessTokenRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.GenerateAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -def test_generate_access_token_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - client.generate_access_token() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GenerateAccessTokenRequest() - -@pytest.mark.asyncio -async def test_generate_access_token_async(transport: str = 'grpc_asyncio', request_type=workstations.GenerateAccessTokenRequest): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse( - access_token='access_token_value', - )) - response = await client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == workstations.GenerateAccessTokenRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.GenerateAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -@pytest.mark.asyncio -async def test_generate_access_token_async_from_dict(): - await test_generate_access_token_async(request_type=dict) - - -def test_generate_access_token_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GenerateAccessTokenRequest() - - request.workstation = 'workstation_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - call.return_value = workstations.GenerateAccessTokenResponse() - client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation=workstation_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_generate_access_token_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = workstations.GenerateAccessTokenRequest() - - request.workstation = 'workstation_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse()) - await client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'workstation=workstation_value', - ) in kw['metadata'] - - -def test_generate_access_token_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.GenerateAccessTokenResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.generate_access_token( - workstation='workstation_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].workstation - mock_val = 'workstation_value' - assert arg == mock_val - - -def test_generate_access_token_flattened_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.generate_access_token( - workstations.GenerateAccessTokenRequest(), - workstation='workstation_value', - ) - -@pytest.mark.asyncio -async def test_generate_access_token_flattened_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = workstations.GenerateAccessTokenResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(workstations.GenerateAccessTokenResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.generate_access_token( - workstation='workstation_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].workstation - mock_val = 'workstation_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_generate_access_token_flattened_error_async(): - client = WorkstationsAsyncClient( - 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.generate_access_token( - workstations.GenerateAccessTokenRequest(), - workstation='workstation_value', - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationClusterRequest, - dict, -]) -def test_get_workstation_cluster_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationCluster( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - network='network_value', - subnetwork='subnetwork_value', - control_plane_ip='control_plane_ip_value', - degraded=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.WorkstationCluster.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_workstation_cluster(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationCluster) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.network == 'network_value' - assert response.subnetwork == 'subnetwork_value' - assert response.control_plane_ip == 'control_plane_ip_value' - assert response.degraded is True - - -def test_get_workstation_cluster_rest_required_fields(request_type=workstations.GetWorkstationClusterRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_cluster._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_workstation_cluster._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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationCluster() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # 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 = workstations.WorkstationCluster.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_workstation_cluster(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_workstation_cluster_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_workstation_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_workstation_cluster_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation_cluster") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.GetWorkstationClusterRequest.pb(workstations.GetWorkstationClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = workstations.WorkstationCluster.to_json(workstations.WorkstationCluster()) - - request = workstations.GetWorkstationClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.WorkstationCluster() - - client.get_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_workstation_cluster_rest_bad_request(transport: str = 'rest', request_type=workstations.GetWorkstationClusterRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_workstation_cluster(request) - - -def test_get_workstation_cluster_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationCluster() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.WorkstationCluster.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_workstation_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) - - -def test_get_workstation_cluster_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_cluster( - workstations.GetWorkstationClusterRequest(), - name='name_value', - ) - - -def test_get_workstation_cluster_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationClustersRequest, - dict, -]) -def test_list_workstation_clusters_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationClustersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListWorkstationClustersResponse.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_workstation_clusters(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationClustersPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workstation_clusters_rest_required_fields(request_type=workstations.ListWorkstationClustersRequest): - transport_class = transports.WorkstationsRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstation_clusters._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstation_clusters._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationClustersResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # 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 = workstations.ListWorkstationClustersResponse.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_workstation_clusters(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_workstation_clusters_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_workstation_clusters._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_workstation_clusters_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstation_clusters") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstation_clusters") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListWorkstationClustersRequest.pb(workstations.ListWorkstationClustersRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = workstations.ListWorkstationClustersResponse.to_json(workstations.ListWorkstationClustersResponse()) - - request = workstations.ListWorkstationClustersRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListWorkstationClustersResponse() - - client.list_workstation_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_workstation_clusters_rest_bad_request(transport: str = 'rest', request_type=workstations.ListWorkstationClustersRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_workstation_clusters(request) - - -def test_list_workstation_clusters_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationClustersResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListWorkstationClustersResponse.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_workstation_clusters(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*}/workstationClusters" % client.transport._host, args[1]) - - -def test_list_workstation_clusters_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_clusters( - workstations.ListWorkstationClustersRequest(), - parent='parent_value', - ) - - -def test_list_workstation_clusters_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[], - next_page_token='def', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationClustersResponse( - workstation_clusters=[ - workstations.WorkstationCluster(), - workstations.WorkstationCluster(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListWorkstationClustersResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_workstation_clusters(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.WorkstationCluster) - for i in results) - - pages = list(client.list_workstation_clusters(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", [ - workstations.CreateWorkstationClusterRequest, - dict, -]) -def test_create_workstation_cluster_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["workstation_cluster"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - 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_workstation_cluster(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_workstation_cluster_rest_required_fields(request_type=workstations.CreateWorkstationClusterRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["workstation_cluster_id"] = "" - 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 "workstationClusterId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "workstationClusterId" in jsonified_request - assert jsonified_request["workstationClusterId"] == request_init["workstation_cluster_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["workstationClusterId"] = 'workstation_cluster_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_cluster._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", "workstation_cluster_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "workstationClusterId" in jsonified_request - assert jsonified_request["workstationClusterId"] == 'workstation_cluster_id_value' - - client = WorkstationsClient( - 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_workstation_cluster(request) - - expected_params = [ - ( - "workstationClusterId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_workstation_cluster_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_workstation_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("validateOnly", "workstationClusterId", )) & set(("parent", "workstationClusterId", "workstationCluster", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_workstation_cluster_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation_cluster") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.CreateWorkstationClusterRequest.pb(workstations.CreateWorkstationClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.CreateWorkstationClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_workstation_cluster_rest_bad_request(transport: str = 'rest', request_type=workstations.CreateWorkstationClusterRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["workstation_cluster"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the 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_workstation_cluster(request) - - -def test_create_workstation_cluster_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_workstation_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*}/workstationClusters" % client.transport._host, args[1]) - - -def test_create_workstation_cluster_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_cluster( - workstations.CreateWorkstationClusterRequest(), - parent='parent_value', - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - workstation_cluster_id='workstation_cluster_id_value', - ) - - -def test_create_workstation_cluster_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationClusterRequest, - dict, -]) -def test_update_workstation_cluster_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} - request_init["workstation_cluster"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - 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_workstation_cluster(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_workstation_cluster_rest_required_fields(request_type=workstations.UpdateWorkstationClusterRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_cluster._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_workstation_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = WorkstationsClient( - 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_workstation_cluster(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_workstation_cluster_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_workstation_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstationCluster", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_workstation_cluster_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation_cluster") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.UpdateWorkstationClusterRequest.pb(workstations.UpdateWorkstationClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.UpdateWorkstationClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_workstation_cluster_rest_bad_request(transport: str = 'rest', request_type=workstations.UpdateWorkstationClusterRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} - request_init["workstation_cluster"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'control_plane_ip': 'control_plane_ip_value', 'private_cluster_config': {'enable_private_endpoint': True, 'cluster_hostname': 'cluster_hostname_value', 'service_attachment_uri': 'service_attachment_uri_value', 'allowed_projects': ['allowed_projects_value1', 'allowed_projects_value2']}, 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the 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_workstation_cluster(request) - - -def test_update_workstation_cluster_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - 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 = {'workstation_cluster': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - workstation_cluster=workstations.WorkstationCluster(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_workstation_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{workstation_cluster.name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) - - -def test_update_workstation_cluster_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_cluster( - workstations.UpdateWorkstationClusterRequest(), - workstation_cluster=workstations.WorkstationCluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_workstation_cluster_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationClusterRequest, - dict, -]) -def test_delete_workstation_cluster_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_workstation_cluster(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_workstation_cluster_rest_required_fields(request_type=workstations.DeleteWorkstationClusterRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_cluster._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_workstation_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("etag", "force", "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 = WorkstationsClient( - 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_workstation_cluster(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_workstation_cluster_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_workstation_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("etag", "force", "validateOnly", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_workstation_cluster_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation_cluster") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.DeleteWorkstationClusterRequest.pb(workstations.DeleteWorkstationClusterRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.DeleteWorkstationClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_workstation_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_workstation_cluster_rest_bad_request(transport: str = 'rest', request_type=workstations.DeleteWorkstationClusterRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_workstation_cluster(request) - - -def test_delete_workstation_cluster_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_workstation_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*}" % client.transport._host, args[1]) - - -def test_delete_workstation_cluster_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_cluster( - workstations.DeleteWorkstationClusterRequest(), - name='name_value', - ) - - -def test_delete_workstation_cluster_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationConfigRequest, - dict, -]) -def test_get_workstation_config_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationConfig( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - degraded=True, - enable_audit_agent=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.WorkstationConfig.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_workstation_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.WorkstationConfig) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.degraded is True - assert response.enable_audit_agent is True - - -def test_get_workstation_config_rest_required_fields(request_type=workstations.GetWorkstationConfigRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_workstation_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # 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 = workstations.WorkstationConfig.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_workstation_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_workstation_config_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_workstation_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_workstation_config_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation_config") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.GetWorkstationConfigRequest.pb(workstations.GetWorkstationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = workstations.WorkstationConfig.to_json(workstations.WorkstationConfig()) - - request = workstations.GetWorkstationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.WorkstationConfig() - - client.get_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_workstation_config_rest_bad_request(transport: str = 'rest', request_type=workstations.GetWorkstationConfigRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_workstation_config(request) - - -def test_get_workstation_config_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.WorkstationConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.WorkstationConfig.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_workstation_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) - - -def test_get_workstation_config_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_config( - workstations.GetWorkstationConfigRequest(), - name='name_value', - ) - - -def test_get_workstation_config_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationConfigsRequest, - dict, -]) -def test_list_workstation_configs_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListWorkstationConfigsResponse.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_workstation_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workstation_configs_rest_required_fields(request_type=workstations.ListWorkstationConfigsRequest): - transport_class = transports.WorkstationsRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstation_configs._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstation_configs._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # 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 = workstations.ListWorkstationConfigsResponse.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_workstation_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_workstation_configs_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_workstation_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_workstation_configs_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstation_configs") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstation_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListWorkstationConfigsRequest.pb(workstations.ListWorkstationConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = workstations.ListWorkstationConfigsResponse.to_json(workstations.ListWorkstationConfigsResponse()) - - request = workstations.ListWorkstationConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListWorkstationConfigsResponse() - - client.list_workstation_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_workstation_configs_rest_bad_request(transport: str = 'rest', request_type=workstations.ListWorkstationConfigsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_workstation_configs(request) - - -def test_list_workstation_configs_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListWorkstationConfigsResponse.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_workstation_configs(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs" % client.transport._host, args[1]) - - -def test_list_workstation_configs_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_configs( - workstations.ListWorkstationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_workstation_configs_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListWorkstationConfigsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - pager = client.list_workstation_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.WorkstationConfig) - for i in results) - - pages = list(client.list_workstation_configs(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", [ - workstations.ListUsableWorkstationConfigsRequest, - dict, -]) -def test_list_usable_workstation_configs_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationConfigsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListUsableWorkstationConfigsResponse.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_usable_workstation_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_usable_workstation_configs_rest_required_fields(request_type=workstations.ListUsableWorkstationConfigsRequest): - transport_class = transports.WorkstationsRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_usable_workstation_configs._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_usable_workstation_configs._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationConfigsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # 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 = workstations.ListUsableWorkstationConfigsResponse.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_usable_workstation_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_usable_workstation_configs_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_usable_workstation_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_usable_workstation_configs_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_usable_workstation_configs") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_usable_workstation_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListUsableWorkstationConfigsRequest.pb(workstations.ListUsableWorkstationConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = workstations.ListUsableWorkstationConfigsResponse.to_json(workstations.ListUsableWorkstationConfigsResponse()) - - request = workstations.ListUsableWorkstationConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListUsableWorkstationConfigsResponse() - - client.list_usable_workstation_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_usable_workstation_configs_rest_bad_request(transport: str = 'rest', request_type=workstations.ListUsableWorkstationConfigsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_usable_workstation_configs(request) - - -def test_list_usable_workstation_configs_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListUsableWorkstationConfigsResponse.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_usable_workstation_configs(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs:listUsable" % client.transport._host, args[1]) - - -def test_list_usable_workstation_configs_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_usable_workstation_configs( - workstations.ListUsableWorkstationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_usable_workstation_configs_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationConfigsResponse( - workstation_configs=[ - workstations.WorkstationConfig(), - workstations.WorkstationConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListUsableWorkstationConfigsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - pager = client.list_usable_workstation_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.WorkstationConfig) - for i in results) - - pages = list(client.list_usable_workstation_configs(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", [ - workstations.CreateWorkstationConfigRequest, - dict, -]) -def test_create_workstation_config_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request_init["workstation_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792, 'accelerators': [{'type_': 'type__value', 'count': 553}]}}, 'persistent_directories': [{'mount_path': 'mount_path_value', 'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'readiness_checks': [{'path': 'path_value', 'port': 453}], 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}], 'enable_audit_agent': True} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - 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_workstation_config(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_workstation_config_rest_required_fields(request_type=workstations.CreateWorkstationConfigRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["workstation_config_id"] = "" - 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 "workstationConfigId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "workstationConfigId" in jsonified_request - assert jsonified_request["workstationConfigId"] == request_init["workstation_config_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["workstationConfigId"] = 'workstation_config_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation_config._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", "workstation_config_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "workstationConfigId" in jsonified_request - assert jsonified_request["workstationConfigId"] == 'workstation_config_id_value' - - client = WorkstationsClient( - 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_workstation_config(request) - - expected_params = [ - ( - "workstationConfigId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_workstation_config_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_workstation_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("validateOnly", "workstationConfigId", )) & set(("parent", "workstationConfigId", "workstationConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_workstation_config_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation_config") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.CreateWorkstationConfigRequest.pb(workstations.CreateWorkstationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.CreateWorkstationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_workstation_config_rest_bad_request(transport: str = 'rest', request_type=workstations.CreateWorkstationConfigRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - request_init["workstation_config"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792, 'accelerators': [{'type_': 'type__value', 'count': 553}]}}, 'persistent_directories': [{'mount_path': 'mount_path_value', 'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'readiness_checks': [{'path': 'path_value', 'port': 453}], 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}], 'enable_audit_agent': True} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the 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_workstation_config(request) - - -def test_create_workstation_config_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_workstation_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*}/workstationConfigs" % client.transport._host, args[1]) - - -def test_create_workstation_config_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_config( - workstations.CreateWorkstationConfigRequest(), - parent='parent_value', - workstation_config=workstations.WorkstationConfig(name='name_value'), - workstation_config_id='workstation_config_id_value', - ) - - -def test_create_workstation_config_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationConfigRequest, - dict, -]) -def test_update_workstation_config_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} - request_init["workstation_config"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792, 'accelerators': [{'type_': 'type__value', 'count': 553}]}}, 'persistent_directories': [{'mount_path': 'mount_path_value', 'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'readiness_checks': [{'path': 'path_value', 'port': 453}], 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}], 'enable_audit_agent': True} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - 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_workstation_config(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_workstation_config_rest_required_fields(request_type=workstations.UpdateWorkstationConfigRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_workstation_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = WorkstationsClient( - 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_workstation_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_workstation_config_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_workstation_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstationConfig", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_workstation_config_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation_config") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.UpdateWorkstationConfigRequest.pb(workstations.UpdateWorkstationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.UpdateWorkstationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_workstation_config_rest_bad_request(transport: str = 'rest', request_type=workstations.UpdateWorkstationConfigRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} - request_init["workstation_config"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'idle_timeout': {'seconds': 751, 'nanos': 543}, 'running_timeout': {}, 'host': {'gce_instance': {'machine_type': 'machine_type_value', 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'pool_size': 980, 'pooled_instances': 1706, 'disable_public_ip_addresses': True, 'shielded_instance_config': {'enable_secure_boot': True, 'enable_vtpm': True, 'enable_integrity_monitoring': True}, 'confidential_instance_config': {'enable_confidential_compute': True}, 'boot_disk_size_gb': 1792, 'accelerators': [{'type_': 'type__value', 'count': 553}]}}, 'persistent_directories': [{'mount_path': 'mount_path_value', 'gce_pd': {'size_gb': 739, 'fs_type': 'fs_type_value', 'disk_type': 'disk_type_value', 'source_snapshot': 'source_snapshot_value', 'reclaim_policy': 1}}], 'container': {'image': 'image_value', 'command': ['command_value1', 'command_value2'], 'args': ['args_value1', 'args_value2'], 'env': {}, 'working_dir': 'working_dir_value', 'run_as_user': 1190}, 'encryption_key': {'kms_key': 'kms_key_value', 'kms_key_service_account': 'kms_key_service_account_value'}, 'readiness_checks': [{'path': 'path_value', 'port': 453}], 'degraded': True, 'conditions': [{'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}], 'enable_audit_agent': True} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the 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_workstation_config(request) - - -def test_update_workstation_config_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - 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 = {'workstation_config': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - workstation_config=workstations.WorkstationConfig(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_workstation_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{workstation_config.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) - - -def test_update_workstation_config_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_config( - workstations.UpdateWorkstationConfigRequest(), - workstation_config=workstations.WorkstationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_workstation_config_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationConfigRequest, - dict, -]) -def test_delete_workstation_config_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = 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_workstation_config(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_workstation_config_rest_required_fields(request_type=workstations.DeleteWorkstationConfigRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_workstation_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("etag", "force", "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 = WorkstationsClient( - 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_workstation_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_workstation_config_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_workstation_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("etag", "force", "validateOnly", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_workstation_config_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation_config") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.DeleteWorkstationConfigRequest.pb(workstations.DeleteWorkstationConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.DeleteWorkstationConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_workstation_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_workstation_config_rest_bad_request(transport: str = 'rest', request_type=workstations.DeleteWorkstationConfigRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_workstation_config(request) - - -def test_delete_workstation_config_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_workstation_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}" % client.transport._host, args[1]) - - -def test_delete_workstation_config_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation_config( - workstations.DeleteWorkstationConfigRequest(), - name='name_value', - ) - - -def test_delete_workstation_config_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GetWorkstationRequest, - dict, -]) -def test_get_workstation_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.Workstation( - name='name_value', - display_name='display_name_value', - uid='uid_value', - reconciling=True, - etag='etag_value', - state=workstations.Workstation.State.STATE_STARTING, - host='host_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.Workstation.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_workstation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.Workstation) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.uid == 'uid_value' - assert response.reconciling is True - assert response.etag == 'etag_value' - assert response.state == workstations.Workstation.State.STATE_STARTING - assert response.host == 'host_value' - - -def test_get_workstation_rest_required_fields(request_type=workstations.GetWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation._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_workstation._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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.Workstation() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # 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 = workstations.Workstation.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_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_get_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_get_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.GetWorkstationRequest.pb(workstations.GetWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = workstations.Workstation.to_json(workstations.Workstation()) - - request = workstations.GetWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.Workstation() - - client.get_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.GetWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_workstation(request) - - -def test_get_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.Workstation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.Workstation.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_workstation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) - - -def test_get_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation( - workstations.GetWorkstationRequest(), - name='name_value', - ) - - -def test_get_workstation_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.ListWorkstationsRequest, - dict, -]) -def test_list_workstations_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListWorkstationsResponse.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_workstations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkstationsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_workstations_rest_required_fields(request_type=workstations.ListWorkstationsRequest): - transport_class = transports.WorkstationsRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstations._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_workstations._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # 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 = workstations.ListWorkstationsResponse.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_workstations(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_workstations_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_workstations._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_workstations_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_workstations") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_workstations") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListWorkstationsRequest.pb(workstations.ListWorkstationsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = workstations.ListWorkstationsResponse.to_json(workstations.ListWorkstationsResponse()) - - request = workstations.ListWorkstationsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListWorkstationsResponse() - - client.list_workstations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_workstations_rest_bad_request(transport: str = 'rest', request_type=workstations.ListWorkstationsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_workstations(request) - - -def test_list_workstations_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListWorkstationsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListWorkstationsResponse.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_workstations(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations" % client.transport._host, args[1]) - - -def test_list_workstations_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstations( - workstations.ListWorkstationsRequest(), - parent='parent_value', - ) - - -def test_list_workstations_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListWorkstationsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - pager = client.list_workstations(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.Workstation) - for i in results) - - pages = list(client.list_workstations(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", [ - workstations.ListUsableWorkstationsRequest, - dict, -]) -def test_list_usable_workstations_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListUsableWorkstationsResponse.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_usable_workstations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsableWorkstationsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_usable_workstations_rest_required_fields(request_type=workstations.ListUsableWorkstationsRequest): - transport_class = transports.WorkstationsRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_usable_workstations._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_usable_workstations._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # 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 = workstations.ListUsableWorkstationsResponse.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_usable_workstations(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_usable_workstations_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_usable_workstations._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_usable_workstations_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_list_usable_workstations") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_list_usable_workstations") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.ListUsableWorkstationsRequest.pb(workstations.ListUsableWorkstationsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = workstations.ListUsableWorkstationsResponse.to_json(workstations.ListUsableWorkstationsResponse()) - - request = workstations.ListUsableWorkstationsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.ListUsableWorkstationsResponse() - - client.list_usable_workstations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_usable_workstations_rest_bad_request(transport: str = 'rest', request_type=workstations.ListUsableWorkstationsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_usable_workstations(request) - - -def test_list_usable_workstations_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.ListUsableWorkstationsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.ListUsableWorkstationsResponse.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_usable_workstations(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations:listUsable" % client.transport._host, args[1]) - - -def test_list_usable_workstations_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_usable_workstations( - workstations.ListUsableWorkstationsRequest(), - parent='parent_value', - ) - - -def test_list_usable_workstations_rest_pager(transport: str = 'rest'): - client = WorkstationsClient( - 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 = ( - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - workstations.Workstation(), - ], - next_page_token='abc', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[], - next_page_token='def', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - ], - next_page_token='ghi', - ), - workstations.ListUsableWorkstationsResponse( - workstations=[ - workstations.Workstation(), - workstations.Workstation(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(workstations.ListUsableWorkstationsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - pager = client.list_usable_workstations(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, workstations.Workstation) - for i in results) - - pages = list(client.list_usable_workstations(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", [ - workstations.CreateWorkstationRequest, - dict, -]) -def test_create_workstation_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request_init["workstation"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_value', 'env': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - 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_workstation(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_workstation_rest_required_fields(request_type=workstations.CreateWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["workstation_id"] = "" - 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 "workstationId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "workstationId" in jsonified_request - assert jsonified_request["workstationId"] == request_init["workstation_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["workstationId"] = 'workstation_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_workstation._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", "workstation_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "workstationId" in jsonified_request - assert jsonified_request["workstationId"] == 'workstation_id_value' - - client = WorkstationsClient( - 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_workstation(request) - - expected_params = [ - ( - "workstationId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(("validateOnly", "workstationId", )) & set(("parent", "workstationId", "workstation", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_create_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_create_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.CreateWorkstationRequest.pb(workstations.CreateWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.CreateWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.CreateWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request_init["workstation"] = {'name': 'name_value', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_value', 'env': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the 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_workstation(request) - - -def test_create_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_workstation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{parent=projects/*/locations/*/workstationClusters/*/workstationConfigs/*}/workstations" % client.transport._host, args[1]) - - -def test_create_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation( - workstations.CreateWorkstationRequest(), - parent='parent_value', - workstation=workstations.Workstation(name='name_value'), - workstation_id='workstation_id_value', - ) - - -def test_create_workstation_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.UpdateWorkstationRequest, - dict, -]) -def test_update_workstation_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} - request_init["workstation"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_value', 'env': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - 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_workstation(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_workstation_rest_required_fields(request_type=workstations.UpdateWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation._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_workstation._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", "validate_only", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = WorkstationsClient( - 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_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", "validateOnly", )) & set(("workstation", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_update_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_update_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.UpdateWorkstationRequest.pb(workstations.UpdateWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.UpdateWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.UpdateWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} - request_init["workstation"] = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5', 'display_name': 'display_name_value', 'uid': 'uid_value', 'reconciling': True, 'annotations': {}, 'labels': {}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'delete_time': {}, 'etag': 'etag_value', 'state': 1, 'host': 'host_value', 'env': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the 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_workstation(request) - - -def test_update_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - 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 = {'workstation': {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'}} - - # get truthy value for each flattened field - mock_args = dict( - workstation=workstations.Workstation(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_workstation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{workstation.name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) - - -def test_update_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation( - workstations.UpdateWorkstationRequest(), - workstation=workstations.Workstation(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_workstation_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.DeleteWorkstationRequest, - dict, -]) -def test_delete_workstation_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = 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_workstation(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_workstation_rest_required_fields(request_type=workstations.DeleteWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - 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_workstation._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_workstation._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 = WorkstationsClient( - 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_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(("etag", "validateOnly", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_delete_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_delete_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.DeleteWorkstationRequest.pb(workstations.DeleteWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.DeleteWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.DeleteWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_workstation(request) - - -def test_delete_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_workstation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}" % client.transport._host, args[1]) - - -def test_delete_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.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_workstation( - workstations.DeleteWorkstationRequest(), - name='name_value', - ) - - -def test_delete_workstation_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.StartWorkstationRequest, - dict, -]) -def test_start_workstation_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = 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.start_workstation(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_start_workstation_rest_required_fields(request_type=workstations.StartWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - 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()).start_workstation._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()).start_workstation._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 = WorkstationsClient( - 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.start_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_start_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.start_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_start_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_start_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_start_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.StartWorkstationRequest.pb(workstations.StartWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.StartWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.start_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_start_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.StartWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.start_workstation(request) - - -def test_start_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.start_workstation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:start" % client.transport._host, args[1]) - - -def test_start_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.start_workstation( - workstations.StartWorkstationRequest(), - name='name_value', - ) - - -def test_start_workstation_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.StopWorkstationRequest, - dict, -]) -def test_stop_workstation_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = 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.stop_workstation(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_stop_workstation_rest_required_fields(request_type=workstations.StopWorkstationRequest): - transport_class = transports.WorkstationsRestTransport - - 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()).stop_workstation._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()).stop_workstation._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 = WorkstationsClient( - 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.stop_workstation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_stop_workstation_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.stop_workstation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_stop_workstation_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(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.WorkstationsRestInterceptor, "post_stop_workstation") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_stop_workstation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.StopWorkstationRequest.pb(workstations.StopWorkstationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_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 = workstations.StopWorkstationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.stop_workstation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_stop_workstation_rest_bad_request(transport: str = 'rest', request_type=workstations.StopWorkstationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.stop_workstation(request) - - -def test_stop_workstation_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.stop_workstation(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{name=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:stop" % client.transport._host, args[1]) - - -def test_stop_workstation_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.stop_workstation( - workstations.StopWorkstationRequest(), - name='name_value', - ) - - -def test_stop_workstation_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - workstations.GenerateAccessTokenRequest, - dict, -]) -def test_generate_access_token_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.GenerateAccessTokenResponse( - access_token='access_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = workstations.GenerateAccessTokenResponse.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.generate_access_token(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, workstations.GenerateAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -def test_generate_access_token_rest_required_fields(request_type=workstations.GenerateAccessTokenRequest): - transport_class = transports.WorkstationsRestTransport - - request_init = {} - request_init["workstation"] = "" - 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()).generate_access_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["workstation"] = 'workstation_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_access_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "workstation" in jsonified_request - assert jsonified_request["workstation"] == 'workstation_value' - - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = workstations.GenerateAccessTokenResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # 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 - - pb_return_value = workstations.GenerateAccessTokenResponse.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.generate_access_token(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_generate_access_token_rest_unset_required_fields(): - transport = transports.WorkstationsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.generate_access_token._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("workstation", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_access_token_rest_interceptors(null_interceptor): - transport = transports.WorkstationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.WorkstationsRestInterceptor(), - ) - client = WorkstationsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "post_generate_access_token") as post, \ - mock.patch.object(transports.WorkstationsRestInterceptor, "pre_generate_access_token") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = workstations.GenerateAccessTokenRequest.pb(workstations.GenerateAccessTokenRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = workstations.GenerateAccessTokenResponse.to_json(workstations.GenerateAccessTokenResponse()) - - request = workstations.GenerateAccessTokenRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = workstations.GenerateAccessTokenResponse() - - client.generate_access_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_generate_access_token_rest_bad_request(transport: str = 'rest', request_type=workstations.GenerateAccessTokenRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.generate_access_token(request) - - -def test_generate_access_token_rest_flattened(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = workstations.GenerateAccessTokenResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'workstation': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4/workstations/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - workstation='workstation_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 = workstations.GenerateAccessTokenResponse.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.generate_access_token(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta/{workstation=projects/*/locations/*/workstationClusters/*/workstationConfigs/*/workstations/*}:generateAccessToken" % client.transport._host, args[1]) - - -def test_generate_access_token_rest_flattened_error(transport: str = 'rest'): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.generate_access_token( - workstations.GenerateAccessTokenRequest(), - workstation='workstation_value', - ) - - -def test_generate_access_token_rest_error(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WorkstationsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = WorkstationsClient( - 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 = WorkstationsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WorkstationsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = WorkstationsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.WorkstationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.WorkstationsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.WorkstationsGrpcTransport, - transports.WorkstationsGrpcAsyncIOTransport, - transports.WorkstationsRestTransport, -]) -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 = WorkstationsClient.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 = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.WorkstationsGrpcTransport, - ) - -def test_workstations_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.WorkstationsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_workstations_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.workstations_v1beta.services.workstations.transports.WorkstationsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.WorkstationsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_workstation_cluster', - 'list_workstation_clusters', - 'create_workstation_cluster', - 'update_workstation_cluster', - 'delete_workstation_cluster', - 'get_workstation_config', - 'list_workstation_configs', - 'list_usable_workstation_configs', - 'create_workstation_config', - 'update_workstation_config', - 'delete_workstation_config', - 'get_workstation', - 'list_workstations', - 'list_usable_workstations', - 'create_workstation', - 'update_workstation', - 'delete_workstation', - 'start_workstation', - 'stop_workstation', - 'generate_access_token', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - 'get_operation', - 'cancel_operation', - 'delete_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_workstations_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.workstations_v1beta.services.workstations.transports.WorkstationsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WorkstationsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_workstations_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.workstations_v1beta.services.workstations.transports.WorkstationsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WorkstationsTransport() - adc.assert_called_once() - - -def test_workstations_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) - WorkstationsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.WorkstationsGrpcTransport, - transports.WorkstationsGrpcAsyncIOTransport, - ], -) -def test_workstations_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.WorkstationsGrpcTransport, - transports.WorkstationsGrpcAsyncIOTransport, - transports.WorkstationsRestTransport, - ], -) -def test_workstations_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.WorkstationsGrpcTransport, grpc_helpers), - (transports.WorkstationsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_workstations_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( - "workstations.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="workstations.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) -def test_workstations_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_workstations_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.WorkstationsRestTransport ( - 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_workstations_rest_lro_client(): - client = WorkstationsClient( - 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_workstations_host_no_port(transport_name): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='workstations.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'workstations.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://workstations.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_workstations_host_with_port(transport_name): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='workstations.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'workstations.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://workstations.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_workstations_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = WorkstationsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = WorkstationsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_workstation_cluster._session - session2 = client2.transport.get_workstation_cluster._session - assert session1 != session2 - session1 = client1.transport.list_workstation_clusters._session - session2 = client2.transport.list_workstation_clusters._session - assert session1 != session2 - session1 = client1.transport.create_workstation_cluster._session - session2 = client2.transport.create_workstation_cluster._session - assert session1 != session2 - session1 = client1.transport.update_workstation_cluster._session - session2 = client2.transport.update_workstation_cluster._session - assert session1 != session2 - session1 = client1.transport.delete_workstation_cluster._session - session2 = client2.transport.delete_workstation_cluster._session - assert session1 != session2 - session1 = client1.transport.get_workstation_config._session - session2 = client2.transport.get_workstation_config._session - assert session1 != session2 - session1 = client1.transport.list_workstation_configs._session - session2 = client2.transport.list_workstation_configs._session - assert session1 != session2 - session1 = client1.transport.list_usable_workstation_configs._session - session2 = client2.transport.list_usable_workstation_configs._session - assert session1 != session2 - session1 = client1.transport.create_workstation_config._session - session2 = client2.transport.create_workstation_config._session - assert session1 != session2 - session1 = client1.transport.update_workstation_config._session - session2 = client2.transport.update_workstation_config._session - assert session1 != session2 - session1 = client1.transport.delete_workstation_config._session - session2 = client2.transport.delete_workstation_config._session - assert session1 != session2 - session1 = client1.transport.get_workstation._session - session2 = client2.transport.get_workstation._session - assert session1 != session2 - session1 = client1.transport.list_workstations._session - session2 = client2.transport.list_workstations._session - assert session1 != session2 - session1 = client1.transport.list_usable_workstations._session - session2 = client2.transport.list_usable_workstations._session - assert session1 != session2 - session1 = client1.transport.create_workstation._session - session2 = client2.transport.create_workstation._session - assert session1 != session2 - session1 = client1.transport.update_workstation._session - session2 = client2.transport.update_workstation._session - assert session1 != session2 - session1 = client1.transport.delete_workstation._session - session2 = client2.transport.delete_workstation._session - assert session1 != session2 - session1 = client1.transport.start_workstation._session - session2 = client2.transport.start_workstation._session - assert session1 != session2 - session1 = client1.transport.stop_workstation._session - session2 = client2.transport.stop_workstation._session - assert session1 != session2 - session1 = client1.transport.generate_access_token._session - session2 = client2.transport.generate_access_token._session - assert session1 != session2 -def test_workstations_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WorkstationsGrpcTransport( - 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_workstations_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WorkstationsGrpcAsyncIOTransport( - 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.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) -def test_workstations_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.WorkstationsGrpcTransport, transports.WorkstationsGrpcAsyncIOTransport]) -def test_workstations_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_workstations_grpc_lro_client(): - client = WorkstationsClient( - 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_workstations_grpc_lro_async_client(): - client = WorkstationsAsyncClient( - 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_workstation_path(): - project = "squid" - location = "clam" - workstation_cluster = "whelk" - workstation_config = "octopus" - workstation = "oyster" - expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}/workstations/{workstation}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, workstation=workstation, ) - actual = WorkstationsClient.workstation_path(project, location, workstation_cluster, workstation_config, workstation) - assert expected == actual - - -def test_parse_workstation_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "workstation_cluster": "mussel", - "workstation_config": "winkle", - "workstation": "nautilus", - } - path = WorkstationsClient.workstation_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_workstation_path(path) - assert expected == actual - -def test_workstation_cluster_path(): - project = "scallop" - location = "abalone" - workstation_cluster = "squid" - expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}".format(project=project, location=location, workstation_cluster=workstation_cluster, ) - actual = WorkstationsClient.workstation_cluster_path(project, location, workstation_cluster) - assert expected == actual - - -def test_parse_workstation_cluster_path(): - expected = { - "project": "clam", - "location": "whelk", - "workstation_cluster": "octopus", - } - path = WorkstationsClient.workstation_cluster_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_workstation_cluster_path(path) - assert expected == actual - -def test_workstation_config_path(): - project = "oyster" - location = "nudibranch" - workstation_cluster = "cuttlefish" - workstation_config = "mussel" - expected = "projects/{project}/locations/{location}/workstationClusters/{workstation_cluster}/workstationConfigs/{workstation_config}".format(project=project, location=location, workstation_cluster=workstation_cluster, workstation_config=workstation_config, ) - actual = WorkstationsClient.workstation_config_path(project, location, workstation_cluster, workstation_config) - assert expected == actual - - -def test_parse_workstation_config_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "workstation_cluster": "scallop", - "workstation_config": "abalone", - } - path = WorkstationsClient.workstation_config_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_workstation_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = WorkstationsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = WorkstationsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = WorkstationsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = WorkstationsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = WorkstationsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = WorkstationsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = WorkstationsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = WorkstationsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = WorkstationsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = WorkstationsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = WorkstationsClient.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.WorkstationsTransport, '_prep_wrapped_messages') as prep: - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.WorkstationsTransport, '_prep_wrapped_messages') as prep: - transport_class = WorkstationsClient.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 = WorkstationsAsyncClient( - 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_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/workstationClusters/sample3/workstationConfigs/sample4'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_delete_operation(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_delete_operation_async(transport: str = "grpc"): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_operation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = None - - client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_delete_operation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_delete_operation_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_delete_operation_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_cancel_operation(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc"): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - response = client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - response = await client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - -def test_set_iam_policy_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - -def test_set_iam_policy_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -@pytest.mark.asyncio -async def test_set_iam_policy_from_dict_async(): - client = WorkstationsAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - -def test_get_iam_policy(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_get_iam_policy_from_dict_async(): - client = WorkstationsAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -def test_test_iam_permissions(transport: str = "grpc"): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): - client = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) - ) - - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = WorkstationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = WorkstationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - response = client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_test_iam_permissions_from_dict_async(): - client = WorkstationsAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = WorkstationsClient( - 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 = WorkstationsClient( - 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", [ - (WorkstationsClient, transports.WorkstationsGrpcTransport), - (WorkstationsAsyncClient, transports.WorkstationsGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/packages/google-cloud-workstations/.flake8 b/packages/google-cloud-workstations/.flake8 index 2e438749863d..87f6e408c47d 100644 --- a/packages/google-cloud-workstations/.flake8 +++ b/packages/google-cloud-workstations/.flake8 @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2020 Google LLC +# Copyright 2023 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-workstations/CONTRIBUTING.rst b/packages/google-cloud-workstations/CONTRIBUTING.rst index 91e7a94886cf..197af73fc02e 100644 --- a/packages/google-cloud-workstations/CONTRIBUTING.rst +++ b/packages/google-cloud-workstations/CONTRIBUTING.rst @@ -236,7 +236,7 @@ We support: Supported versions can be found in our ``noxfile.py`` `config`_. -.. _config: https://github.com/googleapis/google-cloud-python/blob/main/noxfile.py +.. _config: https://github.com/googleapis/google-cloud-python/blob/main/packages/google-cloud-workstations/noxfile.py ********** diff --git a/packages/google-cloud-workstations/MANIFEST.in b/packages/google-cloud-workstations/MANIFEST.in index e783f4c6209b..e0a66705318e 100644 --- a/packages/google-cloud-workstations/MANIFEST.in +++ b/packages/google-cloud-workstations/MANIFEST.in @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2020 Google LLC +# Copyright 2023 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-workstations/README.rst b/packages/google-cloud-workstations/README.rst index 354a34b1b556..83626ae1f23b 100644 --- a/packages/google-cloud-workstations/README.rst +++ b/packages/google-cloud-workstations/README.rst @@ -1,9 +1,9 @@ -Python Client for Cloud Workstations API -======================================== +Python Client for Cloud Workstations +==================================== |preview| |pypi| |versions| -`Cloud Workstations API`_: Cloud Workstations API +`Cloud Workstations`_: - `Client Library Documentation`_ - `Product Documentation`_ @@ -14,9 +14,9 @@ Python Client for Cloud Workstations API :target: https://pypi.org/project/google-cloud-workstations/ .. |versions| image:: https://img.shields.io/pypi/pyversions/google-cloud-workstations.svg :target: https://pypi.org/project/google-cloud-workstations/ -.. _Cloud Workstations API: https://cloud.google.com/workstations/docs +.. _Cloud Workstations: https://cloud.google.com/workstations/ .. _Client Library Documentation: https://cloud.google.com/python/docs/reference/workstations/latest -.. _Product Documentation: https://cloud.google.com/workstations/docs +.. _Product Documentation: https://cloud.google.com/workstations/ Quick Start ----------- @@ -25,32 +25,35 @@ 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 Cloud Workstations API.`_ +3. `Enable the Cloud Workstations.`_ 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 -.. _Enable the Cloud Workstations API.: https://cloud.google.com/workstations/docs +.. _Enable the Cloud Workstations.: https://cloud.google.com/workstations/ .. _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. +Install this library in a virtual environment using `venv`_. `venv`_ is a tool that +creates isolated Python environments. These isolated environments can have separate +versions of Python packages, which allows you to isolate one project's dependencies +from the dependencies of other projects. -With `virtualenv`_, it's possible to install this library without needing system +With `venv`_, 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/ +.. _`venv`: https://docs.python.org/3/library/venv.html Code samples and snippets ~~~~~~~~~~~~~~~~~~~~~~~~~ -Code samples and snippets live in the `samples/` folder. +Code samples and snippets live in the `samples/`_ folder. + +.. _samples/: https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-workstations/samples Supported Python Versions @@ -77,10 +80,9 @@ Mac/Linux .. code-block:: console - pip install virtualenv - virtualenv + python3 -m venv source /bin/activate - /bin/pip install google-cloud-workstations + pip install google-cloud-workstations Windows @@ -88,20 +90,19 @@ Windows .. code-block:: console - pip install virtualenv - virtualenv - \Scripts\activate - \Scripts\pip.exe install google-cloud-workstations + py -m venv + .\\Scripts\activate + pip install google-cloud-workstations Next Steps ~~~~~~~~~~ -- Read the `Client Library Documentation`_ for Cloud Workstations API +- Read the `Client Library Documentation`_ for Cloud Workstations to see other available methods on the client. -- Read the `Cloud Workstations API Product documentation`_ to learn +- Read the `Cloud Workstations Product documentation`_ to learn more about the product and see How-to Guides. - View this `README`_ to see the full list of Cloud APIs that we cover. -.. _Cloud Workstations API Product documentation: https://cloud.google.com/workstations/docs +.. _Cloud Workstations Product documentation: https://cloud.google.com/workstations/ .. _README: https://github.com/googleapis/google-cloud-python/blob/main/README.rst diff --git a/packages/google-cloud-workstations/docs/conf.py b/packages/google-cloud-workstations/docs/conf.py index c2f96079022d..919d2e7028f8 100644 --- a/packages/google-cloud-workstations/docs/conf.py +++ b/packages/google-cloud-workstations/docs/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2021 Google LLC +# Copyright 2023 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-workstations/docs/index.rst b/packages/google-cloud-workstations/docs/index.rst index 65e3e059c9c3..f674c06f338b 100644 --- a/packages/google-cloud-workstations/docs/index.rst +++ b/packages/google-cloud-workstations/docs/index.rst @@ -2,7 +2,7 @@ .. include:: multiprocessing.rst -This package includes clients for multiple versions of Cloud Workstations API. +This package includes clients for multiple versions of Cloud Workstations. By default, you will get version ``workstations_v1``. diff --git a/packages/google-cloud-workstations/noxfile.py b/packages/google-cloud-workstations/noxfile.py index 6f5debd52f23..9a2acd8b6787 100644 --- a/packages/google-cloud-workstations/noxfile.py +++ b/packages/google-cloud-workstations/noxfile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright 2018 Google LLC +# Copyright 2023 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-workstations/scripts/decrypt-secrets.sh b/packages/google-cloud-workstations/scripts/decrypt-secrets.sh index 21f6d2a26d90..0018b421ddf8 100755 --- a/packages/google-cloud-workstations/scripts/decrypt-secrets.sh +++ b/packages/google-cloud-workstations/scripts/decrypt-secrets.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2015 Google Inc. All rights reserved. +# Copyright 2023 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License.