From 36d7bafadeb8249b784c35e20136315fcc322c09 Mon Sep 17 00:00:00 2001 From: Sofia Leon Date: Wed, 23 Sep 2026 17:02:44 +0000 Subject: [PATCH] feat: update API sources and regenerate --- librarian.yaml | 4 +- .../ads/marketingplatform_admin/__init__.py | 42 + .../__init__.py | 42 + .../gapic_metadata.json | 210 + .../async_client.py | 1737 +- .../marketingplatform_admin_service/client.py | 1747 +- .../marketingplatform_admin_service/pagers.py | 482 + .../transports/base.py | 205 + .../transports/grpc.py | 414 +- .../transports/grpc_asyncio.py | 490 +- .../transports/rest.py | 3587 +++- .../transports/rest_base.py | 236 + .../types/__init__.py | 42 + .../types/marketingplatform_admin.py | 444 + .../types/resources.py | 187 + ...rvice_create_admin_access_binding_async.py | 57 + ...ervice_create_admin_access_binding_sync.py | 57 + ...m_admin_service_create_user_group_async.py | 53 + ..._service_create_user_group_member_async.py | 57 + ...n_service_create_user_group_member_sync.py | 57 + ...rm_admin_service_create_user_group_sync.py | 53 + ...m_admin_service_delete_user_group_async.py | 50 + ..._service_delete_user_group_member_async.py | 50 + ...n_service_delete_user_group_member_sync.py | 50 + ...rm_admin_service_delete_user_group_sync.py | 50 + ..._service_get_admin_access_binding_async.py | 53 + ...n_service_get_admin_access_binding_sync.py | 53 + ...form_admin_service_get_user_group_async.py | 53 + ...min_service_get_user_group_member_async.py | 53 + ...dmin_service_get_user_group_member_sync.py | 53 + ...tform_admin_service_get_user_group_sync.py | 53 + ...ervice_list_admin_access_bindings_async.py | 54 + ...service_list_admin_access_bindings_sync.py | 54 + ...n_service_list_user_group_members_async.py | 54 + ...in_service_list_user_group_members_sync.py | 54 + ...rm_admin_service_list_user_groups_async.py | 54 + ...orm_admin_service_list_user_groups_sync.py | 54 + ...rvice_update_admin_access_binding_async.py | 56 + ...ervice_update_admin_access_binding_sync.py | 56 + ...m_admin_service_update_user_group_async.py | 51 + ..._service_update_user_group_member_async.py | 56 + ...n_service_update_user_group_member_sync.py | 56 + ...rm_admin_service_update_user_group_sync.py | 51 + ...oogle.marketingplatform.admin.v1alpha.json | 2792 ++- .../test_marketingplatform_admin_service.py | 15154 +++++++++++++-- .../google/analytics/data_v1alpha/__init__.py | 8 + .../data_v1alpha/gapic_metadata.json | 15 + .../alpha_analytics_data/async_client.py | 94 + .../services/alpha_analytics_data/client.py | 107 + .../alpha_analytics_data/transports/base.py | 17 + .../alpha_analytics_data/transports/grpc.py | 36 + .../transports/grpc_asyncio.py | 43 + .../alpha_analytics_data/transports/rest.py | 209 + .../transports/rest_base.py | 17 + .../analytics/data_v1alpha/types/__init__.py | 8 + .../data_v1alpha/types/analytics_data_api.py | 79 + .../analytics/data_v1alpha/types/data.py | 266 + ...nerated_alpha_analytics_data_chat_async.py | 54 + ...enerated_alpha_analytics_data_chat_sync.py | 54 + ...etadata_google.analytics.data.v1alpha.json | 153 + .../data_v1alpha/test_alpha_analytics_data.py | 623 +- .../google/apps/chat/__init__.py | 14 + .../google/apps/chat_v1/__init__.py | 16 + .../google/apps/chat_v1/gapic_metadata.json | 45 + .../services/chat_service/async_client.py | 398 +- .../chat_v1/services/chat_service/client.py | 404 +- .../chat_v1/services/chat_service/pagers.py | 157 + .../services/chat_service/transports/base.py | 49 + .../services/chat_service/transports/grpc.py | 111 + .../chat_service/transports/grpc_asyncio.py | 129 + .../services/chat_service/transports/rest.py | 574 + .../chat_service/transports/rest_base.py | 51 + .../google/apps/chat_v1/types/__init__.py | 16 + .../google/apps/chat_v1/types/annotation.py | 8 +- .../chat_v1/types/app_command_metadata.py | 76 + .../google/apps/chat_v1/types/message.py | 38 +- .../google/apps/chat_v1/types/message_pin.py | 163 + .../google/apps/chat_v1/types/space.py | 99 +- .../google/apps/chat_v1/types/space_setup.py | 28 +- ...d_chat_service_create_message_pin_async.py | 57 + ...ed_chat_service_create_message_pin_sync.py | 57 + ...d_chat_service_delete_message_pin_async.py | 50 + ...ed_chat_service_delete_message_pin_sync.py | 50 + ...ed_chat_service_list_message_pins_async.py | 54 + ...ted_chat_service_list_message_pins_sync.py | 54 + .../snippet_metadata_google.chat.v1.json | 485 + .../unit/gapic/chat_v1/test_chat_service.py | 11970 +++++++----- .../services/agent_registry/async_client.py | 2 - .../services/agent_registry/client.py | 2 - .../cloud/agentregistry_v1/types/binding.py | 2 +- ...ted_agent_registry_create_binding_async.py | 1 - ...ated_agent_registry_create_binding_sync.py | 1 - ...ted_agent_registry_update_binding_async.py | 1 - ...ated_agent_registry_update_binding_sync.py | 1 - ...etadata_google.cloud.agentregistry.v1.json | 56 +- .../cloud/bigtable_admin_v2/types/table.py | 33 + .../test_bigtable_table_admin.py | 3 + .../data_a2a_service.rst | 6 + .../geminidataanalytics_v1alpha/services_.rst | 1 + .../data_a2a_service.rst | 6 + .../geminidataanalytics_v1beta/services_.rst | 1 + .../cloud/geminidataanalytics/__init__.py | 14 + .../cloud/geminidataanalytics_v1/__init__.py | 14 + .../gapic_metadata.json | 45 + .../data_agent_service/async_client.py | 285 + .../services/data_agent_service/client.py | 283 + .../data_agent_service/transports/base.py | 31 + .../data_agent_service/transports/grpc.py | 66 + .../transports/grpc_asyncio.py | 77 + .../data_agent_service/transports/rest.py | 448 + .../transports/rest_base.py | 35 + .../data_chat_service/async_client.py | 131 + .../services/data_chat_service/client.py | 128 + .../data_chat_service/transports/base.py | 14 + .../data_chat_service/transports/grpc.py | 28 + .../transports/grpc_asyncio.py | 34 + .../data_chat_service/transports/rest.py | 215 + .../data_chat_service/transports/rest_base.py | 17 + .../geminidataanalytics_v1/types/__init__.py | 14 + .../geminidataanalytics_v1/types/context.py | 212 +- .../types/conversation.py | 59 +- .../types/data_agent.py | 72 + .../types/data_agent_service.py | 168 + .../types/data_chat_service.py | 16 +- .../geminidataanalytics_v1alpha/__init__.py | 122 + .../gapic_metadata.json | 109 + .../services/data_a2a_service/__init__.py | 22 + .../services/data_a2a_service/async_client.py | 1017 + .../services/data_a2a_service/client.py | 1306 ++ .../data_a2a_service/transports/README.rst | 10 + .../data_a2a_service/transports/__init__.py | 36 + .../data_a2a_service/transports/base.py | 298 + .../data_a2a_service/transports/grpc.py | 530 + .../transports/grpc_asyncio.py | 597 + .../data_a2a_service/transports/rest.py | 1765 ++ .../data_a2a_service/transports/rest_base.py | 240 + .../data_agent_service/async_client.py | 287 + .../services/data_agent_service/client.py | 307 + .../data_agent_service/transports/base.py | 31 + .../data_agent_service/transports/grpc.py | 66 + .../transports/grpc_asyncio.py | 77 + .../data_agent_service/transports/rest.py | 448 + .../transports/rest_base.py | 35 + .../data_chat_service/async_client.py | 137 +- .../services/data_chat_service/client.py | 156 +- .../data_chat_service/transports/base.py | 14 + .../data_chat_service/transports/grpc.py | 31 +- .../transports/grpc_asyncio.py | 37 +- .../data_chat_service/transports/rest.py | 215 + .../data_chat_service/transports/rest_base.py | 17 + .../types/__init__.py | 118 + .../types/context.py | 606 +- .../types/conversation.py | 74 +- .../types/data_a2a_service.py | 1539 ++ .../types/data_agent.py | 85 + .../types/data_agent_service.py | 168 + .../types/data_chat_service.py | 194 +- .../types/datasource.py | 70 +- .../types/usage.py | 52 + .../geminidataanalytics_v1beta/__init__.py | 100 + .../gapic_metadata.json | 109 + .../services/data_a2a_service/__init__.py | 22 + .../services/data_a2a_service/async_client.py | 1017 + .../services/data_a2a_service/client.py | 1306 ++ .../data_a2a_service/transports/README.rst | 10 + .../data_a2a_service/transports/__init__.py | 36 + .../data_a2a_service/transports/base.py | 298 + .../data_a2a_service/transports/grpc.py | 530 + .../transports/grpc_asyncio.py | 597 + .../data_a2a_service/transports/rest.py | 1765 ++ .../data_a2a_service/transports/rest_base.py | 240 + .../data_agent_service/async_client.py | 285 + .../services/data_agent_service/client.py | 283 + .../data_agent_service/transports/base.py | 31 + .../data_agent_service/transports/grpc.py | 66 + .../transports/grpc_asyncio.py | 77 + .../data_agent_service/transports/rest.py | 448 + .../transports/rest_base.py | 35 + .../data_chat_service/async_client.py | 132 + .../services/data_chat_service/client.py | 129 + .../data_chat_service/transports/base.py | 14 + .../data_chat_service/transports/grpc.py | 28 + .../transports/grpc_asyncio.py | 34 + .../data_chat_service/transports/rest.py | 215 + .../data_chat_service/transports/rest_base.py | 17 + .../types/__init__.py | 96 + .../types/context.py | 199 +- .../types/conversation.py | 59 +- .../types/data_a2a_service.py | 1539 ++ .../types/data_agent.py | 72 + .../types/data_agent_service.py | 168 + .../types/data_chat_service.py | 30 +- .../types/datasource.py | 11 +- .../geminidataanalytics_v1beta/types/usage.py | 52 + ..._retrieve_agent_ops_observability_async.py | 54 + ...e_retrieve_agent_ops_observability_sync.py | 54 + ...rvice_set_agent_ops_observability_async.py | 58 + ...ervice_set_agent_ops_observability_sync.py | 58 + ..._chat_service_update_conversation_async.py | 56 + ...a_chat_service_update_conversation_sync.py | 56 + ...d_data_a2a_service_get_agent_card_async.py | 51 + ...ed_data_a2a_service_get_agent_card_sync.py | 51 + ...ted_data_a2a_service_send_message_async.py | 51 + ...ated_data_a2a_service_send_message_sync.py | 51 + ...2a_service_send_streaming_message_async.py | 52 + ...a2a_service_send_streaming_message_sync.py | 52 + ..._retrieve_agent_ops_observability_async.py | 54 + ...e_retrieve_agent_ops_observability_sync.py | 54 + ...rvice_set_agent_ops_observability_async.py | 58 + ...ervice_set_agent_ops_observability_sync.py | 58 + ..._chat_service_update_conversation_async.py | 56 + ...a_chat_service_update_conversation_sync.py | 56 + ...d_data_a2a_service_get_agent_card_async.py | 51 + ...ed_data_a2a_service_get_agent_card_sync.py | 51 + ...ted_data_a2a_service_send_message_async.py | 51 + ...ated_data_a2a_service_send_message_sync.py | 51 + ...2a_service_send_streaming_message_async.py | 52 + ...a2a_service_send_streaming_message_sync.py | 52 + ..._retrieve_agent_ops_observability_async.py | 54 + ...e_retrieve_agent_ops_observability_sync.py | 54 + ...rvice_set_agent_ops_observability_async.py | 58 + ...ervice_set_agent_ops_observability_sync.py | 58 + ..._chat_service_update_conversation_async.py | 56 + ...a_chat_service_update_conversation_sync.py | 56 + ...a_google.cloud.geminidataanalytics.v1.json | 515 + ...gle.cloud.geminidataanalytics.v1alpha.json | 1510 +- ...ogle.cloud.geminidataanalytics.v1beta.json | 1510 +- .../test_data_agent_service.py | 2971 ++- .../test_data_chat_service.py | 887 +- .../test_data_a2a_service.py | 5389 ++++++ .../test_data_agent_service.py | 3165 +++- .../test_data_chat_service.py | 953 +- .../test_data_a2a_service.py | 5389 ++++++ .../test_data_agent_service.py | 2967 ++- .../test_data_chat_service.py | 888 +- .../google/cloud/lustre/__init__.py | 42 + .../google/cloud/lustre_v1/__init__.py | 44 + .../cloud/lustre_v1/gapic_metadata.json | 150 + .../lustre_v1/services/lustre/async_client.py | 1795 +- .../cloud/lustre_v1/services/lustre/client.py | 1811 +- .../cloud/lustre_v1/services/lustre/pagers.py | 318 +- .../services/lustre/transports/base.py | 198 +- .../services/lustre/transports/grpc.py | 358 +- .../lustre/transports/grpc_asyncio.py | 434 +- .../services/lustre/transports/rest.py | 3239 +++- .../services/lustre/transports/rest_base.py | 234 +- .../google/cloud/lustre_v1/types/__init__.py | 42 + .../cloud/lustre_v1/types/directory_policy.py | 225 + .../google/cloud/lustre_v1/types/instance.py | 497 +- .../google/cloud/lustre_v1/types/mirror.py | 488 + .../google/cloud/lustre_v1/types/transfer.py | 25 +- ...ed_lustre_create_directory_policy_async.py | 62 + ...ted_lustre_create_directory_policy_sync.py | 62 + ..._generated_lustre_create_instance_async.py | 1 - ...1_generated_lustre_create_instance_sync.py | 1 - ...v1_generated_lustre_create_mirror_async.py | 63 + ..._v1_generated_lustre_create_mirror_sync.py | 63 + ...ed_lustre_delete_directory_policy_async.py | 57 + ...ted_lustre_delete_directory_policy_sync.py | 57 + ...v1_generated_lustre_delete_mirror_async.py | 57 + ..._v1_generated_lustre_delete_mirror_sync.py | 57 + ...rated_lustre_get_directory_policy_async.py | 53 + ...erated_lustre_get_directory_policy_sync.py | 53 + ...re_v1_generated_lustre_get_mirror_async.py | 53 + ...tre_v1_generated_lustre_get_mirror_sync.py | 53 + ...ed_lustre_list_directory_policies_async.py | 54 + ...ted_lustre_list_directory_policies_sync.py | 54 + ..._v1_generated_lustre_list_mirrors_async.py | 54 + ...e_v1_generated_lustre_list_mirrors_sync.py | 54 + ...ted_lustre_reschedule_maintenance_async.py | 61 + ...ated_lustre_reschedule_maintenance_sync.py | 61 + ..._generated_lustre_update_instance_async.py | 1 - ...1_generated_lustre_update_instance_sync.py | 1 - ...v1_generated_lustre_update_mirror_async.py | 61 + ..._v1_generated_lustre_update_mirror_sync.py | 61 + ...ippet_metadata_google.cloud.lustre.v1.json | 2062 +- packages/google-cloud-lustre/setup.py | 1 + .../testing/constraints-3.10.txt | 1 + .../testing/constraints-3.11.txt | 1 + .../testing/constraints-3.12.txt | 1 + .../testing/constraints-3.13.txt | 1 + .../testing/constraints-3.14.txt | 1 + .../testing/constraints-3.15.txt | 1 + .../tests/unit/gapic/lustre_v1/test_lustre.py | 15794 ++++++++++++---- .../types/incident_list.py | 18 +- .../monitoring_dashboard_v1/types/widget.py | 2 +- .../google/cloud/parametermanager/__init__.py | 36 + .../cloud/parametermanager_v1/__init__.py | 36 + .../parametermanager_v1/gapic_metadata.json | 165 + .../parameter_manager/async_client.py | 1304 ++ .../services/parameter_manager/client.py | 1311 ++ .../services/parameter_manager/pagers.py | 312 + .../parameter_manager/transports/base.py | 160 + .../parameter_manager/transports/grpc.py | 291 + .../transports/grpc_asyncio.py | 358 + .../parameter_manager/transports/rest.py | 2723 ++- .../parameter_manager/transports/rest_base.py | 186 + .../parametermanager_v1/types/__init__.py | 36 + .../parametermanager_v1/types/service.py | 787 +- ...parameter_manager_create_template_async.py | 54 + ..._parameter_manager_create_template_sync.py | 54 + ...r_manager_create_template_version_async.py | 58 + ...er_manager_create_template_version_sync.py | 58 + ...parameter_manager_delete_template_async.py | 50 + ..._parameter_manager_delete_template_sync.py | 50 + ...r_manager_delete_template_version_async.py | 50 + ...er_manager_delete_template_version_sync.py | 50 + ...ed_parameter_manager_get_template_async.py | 53 + ...ted_parameter_manager_get_template_sync.py | 53 + ...eter_manager_get_template_version_async.py | 53 + ...meter_manager_get_template_version_sync.py | 53 + ...er_manager_list_template_versions_async.py | 54 + ...ter_manager_list_template_versions_sync.py | 54 + ..._parameter_manager_list_templates_async.py | 54 + ...d_parameter_manager_list_templates_sync.py | 54 + ...r_manager_render_template_version_async.py | 54 + ...er_manager_render_template_version_sync.py | 54 + ...parameter_manager_update_template_async.py | 51 + ..._parameter_manager_update_template_sync.py | 51 + ...r_manager_update_template_version_async.py | 56 + ...er_manager_update_template_version_sync.py | 56 + ...data_google.cloud.parametermanager.v1.json | 2313 ++- .../test_parameter_manager.py | 13614 ++++++++++--- .../sql_instances_service/async_client.py | 19 +- .../services/sql_instances_service/client.py | 19 +- .../sqladmin_v1/types/cloud_sql_databases.py | 30 + .../sqladmin_v1/types/cloud_sql_instances.py | 283 + .../sqladmin_v1/types/cloud_sql_users.py | 30 + .../sql_instances_service/async_client.py | 19 +- .../services/sql_instances_service/client.py | 19 +- .../cloud/sqladmin_v1beta4/types/cloud_sql.py | 282 + .../types/cloud_sql_resources.py | 31 + .../sqladmin_v1beta4/types/cloud_sql_users.py | 30 + .../sqladmin_v1/test_sql_databases_service.py | 12 + .../sqladmin_v1/test_sql_instances_service.py | 284 +- .../sqladmin_v1/test_sql_users_service.py | 10 + .../test_sql_backups_service.py | 2 + .../test_sql_databases_service.py | 12 + .../test_sql_instances_service.py | 369 +- .../test_sql_users_service.py | 10 + .../google/cloud/tasks/__init__.py | 24 + .../google/cloud/tasks_v2/__init__.py | 25 + .../google/cloud/tasks_v2/gapic_metadata.json | 60 + .../services/cloud_tasks/async_client.py | 651 +- .../tasks_v2/services/cloud_tasks/client.py | 682 +- .../services/cloud_tasks/transports/base.py | 81 +- .../services/cloud_tasks/transports/grpc.py | 181 +- .../cloud_tasks/transports/grpc_asyncio.py | 212 +- .../services/cloud_tasks/transports/rest.py | 1316 +- .../cloud_tasks/transports/rest_base.py | 85 +- .../google/cloud/tasks_v2/types/__init__.py | 26 + .../google/cloud/tasks_v2/types/cloudtasks.py | 311 +- .../cloud/tasks_v2/types/cmek_config.py | 57 + .../google/cloud/tasks_v2/types/queue.py | 92 +- .../google/cloud/tasks_v2/types/target.py | 347 +- .../google/cloud/tasks_v2/types/task.py | 19 +- ...ed_cloud_tasks_batch_create_tasks_async.py | 61 + ...ted_cloud_tasks_batch_create_tasks_sync.py | 61 + ...ed_cloud_tasks_batch_delete_tasks_async.py | 58 + ...ted_cloud_tasks_batch_delete_tasks_sync.py | 58 + ...rated_cloud_tasks_get_cmek_config_async.py | 53 + ...erated_cloud_tasks_get_cmek_config_sync.py | 53 + ...ed_cloud_tasks_update_cmek_config_async.py | 51 + ...ted_cloud_tasks_update_cmek_config_sync.py | 51 + ...nippet_metadata_google.cloud.tasks.v2.json | 802 +- .../unit/gapic/tasks_v2/test_cloud_tasks.py | 8828 ++++++--- .../types/data_object_search_service.py | 46 +- .../vectorsearch_v1/types/embedding_config.py | 18 +- .../types/data_object_search_service.py | 173 +- 369 files changed, 147252 insertions(+), 19843 deletions(-) create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_admin_access_binding_async.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_admin_access_binding_sync.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_async.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_member_async.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_member_sync.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_sync.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_async.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_member_async.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_member_sync.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_sync.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_admin_access_binding_async.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_admin_access_binding_sync.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_async.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_member_async.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_member_sync.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_sync.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_admin_access_bindings_async.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_admin_access_bindings_sync.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_group_members_async.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_group_members_sync.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_groups_async.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_groups_sync.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_admin_access_binding_async.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_admin_access_binding_sync.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_async.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_member_async.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_member_sync.py create mode 100644 packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_sync.py create mode 100644 packages/google-analytics-data/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_chat_async.py create mode 100644 packages/google-analytics-data/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_chat_sync.py create mode 100644 packages/google-apps-chat/google/apps/chat_v1/types/app_command_metadata.py create mode 100644 packages/google-apps-chat/google/apps/chat_v1/types/message_pin.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_message_pin_async.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_message_pin_sync.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_message_pin_async.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_message_pin_sync.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_message_pins_async.py create mode 100644 packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_message_pins_sync.py create mode 100644 packages/google-cloud-geminidataanalytics/docs/geminidataanalytics_v1alpha/data_a2a_service.rst create mode 100644 packages/google-cloud-geminidataanalytics/docs/geminidataanalytics_v1beta/data_a2a_service.rst create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/__init__.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/async_client.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/client.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/README.rst create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/__init__.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/base.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/grpc.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/grpc_asyncio.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/rest.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/rest_base.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/data_a2a_service.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/usage.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/__init__.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/async_client.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/client.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/README.rst create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/__init__.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/base.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/grpc.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/grpc_asyncio.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/rest.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/rest_base.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_a2a_service.py create mode 100644 packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/usage.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_agent_service_retrieve_agent_ops_observability_async.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_agent_service_retrieve_agent_ops_observability_sync.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_agent_service_set_agent_ops_observability_async.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_agent_service_set_agent_ops_observability_sync.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_chat_service_update_conversation_async.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_chat_service_update_conversation_sync.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_get_agent_card_async.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_get_agent_card_sync.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_send_message_async.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_send_message_sync.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_send_streaming_message_async.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_send_streaming_message_sync.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_agent_service_retrieve_agent_ops_observability_async.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_agent_service_retrieve_agent_ops_observability_sync.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_agent_service_set_agent_ops_observability_async.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_agent_service_set_agent_ops_observability_sync.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_update_conversation_async.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_update_conversation_sync.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_get_agent_card_async.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_get_agent_card_sync.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_send_message_async.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_send_message_sync.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_send_streaming_message_async.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_send_streaming_message_sync.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_agent_service_retrieve_agent_ops_observability_async.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_agent_service_retrieve_agent_ops_observability_sync.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_agent_service_set_agent_ops_observability_async.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_agent_service_set_agent_ops_observability_sync.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_update_conversation_async.py create mode 100644 packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_update_conversation_sync.py create mode 100644 packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_a2a_service.py create mode 100644 packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_a2a_service.py create mode 100644 packages/google-cloud-lustre/google/cloud/lustre_v1/types/directory_policy.py create mode 100644 packages/google-cloud-lustre/google/cloud/lustre_v1/types/mirror.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_directory_policy_async.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_directory_policy_sync.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_mirror_async.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_mirror_sync.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_delete_directory_policy_async.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_delete_directory_policy_sync.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_delete_mirror_async.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_delete_mirror_sync.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_get_directory_policy_async.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_get_directory_policy_sync.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_get_mirror_async.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_get_mirror_sync.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_list_directory_policies_async.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_list_directory_policies_sync.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_list_mirrors_async.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_list_mirrors_sync.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_reschedule_maintenance_async.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_reschedule_maintenance_sync.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_update_mirror_async.py create mode 100644 packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_update_mirror_sync.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_create_template_async.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_create_template_sync.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_create_template_version_async.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_create_template_version_sync.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_delete_template_async.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_delete_template_sync.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_delete_template_version_async.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_delete_template_version_sync.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_get_template_async.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_get_template_sync.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_get_template_version_async.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_get_template_version_sync.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_list_template_versions_async.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_list_template_versions_sync.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_list_templates_async.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_list_templates_sync.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_render_template_version_async.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_render_template_version_sync.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_update_template_async.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_update_template_sync.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_update_template_version_async.py create mode 100644 packages/google-cloud-parametermanager/samples/generated_samples/parametermanager_v1_generated_parameter_manager_update_template_version_sync.py create mode 100644 packages/google-cloud-tasks/google/cloud/tasks_v2/types/cmek_config.py create mode 100644 packages/google-cloud-tasks/samples/generated_samples/cloudtasks_v2_generated_cloud_tasks_batch_create_tasks_async.py create mode 100644 packages/google-cloud-tasks/samples/generated_samples/cloudtasks_v2_generated_cloud_tasks_batch_create_tasks_sync.py create mode 100644 packages/google-cloud-tasks/samples/generated_samples/cloudtasks_v2_generated_cloud_tasks_batch_delete_tasks_async.py create mode 100644 packages/google-cloud-tasks/samples/generated_samples/cloudtasks_v2_generated_cloud_tasks_batch_delete_tasks_sync.py create mode 100644 packages/google-cloud-tasks/samples/generated_samples/cloudtasks_v2_generated_cloud_tasks_get_cmek_config_async.py create mode 100644 packages/google-cloud-tasks/samples/generated_samples/cloudtasks_v2_generated_cloud_tasks_get_cmek_config_sync.py create mode 100644 packages/google-cloud-tasks/samples/generated_samples/cloudtasks_v2_generated_cloud_tasks_update_cmek_config_async.py create mode 100644 packages/google-cloud-tasks/samples/generated_samples/cloudtasks_v2_generated_cloud_tasks_update_cmek_config_sync.py diff --git a/librarian.yaml b/librarian.yaml index 58143336e171..c915902b2450 100644 --- a/librarian.yaml +++ b/librarian.yaml @@ -16,8 +16,8 @@ version: v0.45.0 repo: googleapis/google-cloud-python sources: googleapis: - commit: 2820f045329fc1d000570aee6a39226c3382b2e2 - sha256: 2c82a62b685cb73f44c78a5b91d561f83b9bac4a3057dd108e43e61b3cfc0585 + commit: 9b719a5c153f3ec7a14d5d45d4da720410c7b943 + sha256: fcceaa2004ccc51874effb9669303c042d21ff3e308f1710ce8280acbab8e2a5 tools: pip: - name: black diff --git a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin/__init__.py b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin/__init__.py index e527aa77a355..ff1344d0dd2f 100644 --- a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin/__init__.py +++ b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin/__init__.py @@ -25,47 +25,89 @@ MarketingplatformAdminServiceClient, ) from google.ads.marketingplatform_admin_v1alpha.types.marketingplatform_admin import ( + CreateAdminAccessBindingRequest, CreateAnalyticsAccountLinkRequest, + CreateUserGroupMemberRequest, + CreateUserGroupRequest, DeleteAnalyticsAccountLinkRequest, + DeleteUserGroupMemberRequest, + DeleteUserGroupRequest, FindSalesPartnerManagedClientsRequest, FindSalesPartnerManagedClientsResponse, + GetAdminAccessBindingRequest, GetOrganizationRequest, + GetUserGroupMemberRequest, + GetUserGroupRequest, + ListAdminAccessBindingsRequest, + ListAdminAccessBindingsResponse, ListAnalyticsAccountLinksRequest, ListAnalyticsAccountLinksResponse, ListOrganizationsRequest, ListOrganizationsResponse, + ListUserGroupMembersRequest, + ListUserGroupMembersResponse, + ListUserGroupsRequest, + ListUserGroupsResponse, ReportPropertyUsageRequest, ReportPropertyUsageResponse, SetPropertyServiceLevelRequest, SetPropertyServiceLevelResponse, + UpdateAdminAccessBindingRequest, + UpdateUserGroupMemberRequest, + UpdateUserGroupRequest, ) from google.ads.marketingplatform_admin_v1alpha.types.resources import ( + AdminAccessBinding, AnalyticsAccountLink, AnalyticsPropertyType, AnalyticsServiceLevel, LinkVerificationState, Organization, + OrganizationRole, + UserGroup, + UserGroupMember, ) __all__ = ( "MarketingplatformAdminServiceClient", "MarketingplatformAdminServiceAsyncClient", + "CreateAdminAccessBindingRequest", "CreateAnalyticsAccountLinkRequest", + "CreateUserGroupMemberRequest", + "CreateUserGroupRequest", "DeleteAnalyticsAccountLinkRequest", + "DeleteUserGroupMemberRequest", + "DeleteUserGroupRequest", "FindSalesPartnerManagedClientsRequest", "FindSalesPartnerManagedClientsResponse", + "GetAdminAccessBindingRequest", "GetOrganizationRequest", + "GetUserGroupMemberRequest", + "GetUserGroupRequest", + "ListAdminAccessBindingsRequest", + "ListAdminAccessBindingsResponse", "ListAnalyticsAccountLinksRequest", "ListAnalyticsAccountLinksResponse", "ListOrganizationsRequest", "ListOrganizationsResponse", + "ListUserGroupMembersRequest", + "ListUserGroupMembersResponse", + "ListUserGroupsRequest", + "ListUserGroupsResponse", "ReportPropertyUsageRequest", "ReportPropertyUsageResponse", "SetPropertyServiceLevelRequest", "SetPropertyServiceLevelResponse", + "UpdateAdminAccessBindingRequest", + "UpdateUserGroupMemberRequest", + "UpdateUserGroupRequest", + "AdminAccessBinding", "AnalyticsAccountLink", "Organization", + "UserGroup", + "UserGroupMember", "AnalyticsPropertyType", "AnalyticsServiceLevel", "LinkVerificationState", + "OrganizationRole", ) diff --git a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/__init__.py b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/__init__.py index bfbc659dc54a..45839586ed9c 100644 --- a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/__init__.py +++ b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/__init__.py @@ -37,49 +37,91 @@ MarketingplatformAdminServiceClient, ) from .types.marketingplatform_admin import ( + CreateAdminAccessBindingRequest, CreateAnalyticsAccountLinkRequest, + CreateUserGroupMemberRequest, + CreateUserGroupRequest, DeleteAnalyticsAccountLinkRequest, + DeleteUserGroupMemberRequest, + DeleteUserGroupRequest, FindSalesPartnerManagedClientsRequest, FindSalesPartnerManagedClientsResponse, + GetAdminAccessBindingRequest, GetOrganizationRequest, + GetUserGroupMemberRequest, + GetUserGroupRequest, + ListAdminAccessBindingsRequest, + ListAdminAccessBindingsResponse, ListAnalyticsAccountLinksRequest, ListAnalyticsAccountLinksResponse, ListOrganizationsRequest, ListOrganizationsResponse, + ListUserGroupMembersRequest, + ListUserGroupMembersResponse, + ListUserGroupsRequest, + ListUserGroupsResponse, ReportPropertyUsageRequest, ReportPropertyUsageResponse, SetPropertyServiceLevelRequest, SetPropertyServiceLevelResponse, + UpdateAdminAccessBindingRequest, + UpdateUserGroupMemberRequest, + UpdateUserGroupRequest, ) from .types.resources import ( + AdminAccessBinding, AnalyticsAccountLink, AnalyticsPropertyType, AnalyticsServiceLevel, LinkVerificationState, Organization, + OrganizationRole, + UserGroup, + UserGroupMember, ) __all__ = ( "MarketingplatformAdminServiceAsyncClient", + "AdminAccessBinding", "AnalyticsAccountLink", "AnalyticsPropertyType", "AnalyticsServiceLevel", + "CreateAdminAccessBindingRequest", "CreateAnalyticsAccountLinkRequest", + "CreateUserGroupMemberRequest", + "CreateUserGroupRequest", "DeleteAnalyticsAccountLinkRequest", + "DeleteUserGroupMemberRequest", + "DeleteUserGroupRequest", "FindSalesPartnerManagedClientsRequest", "FindSalesPartnerManagedClientsResponse", + "GetAdminAccessBindingRequest", "GetOrganizationRequest", + "GetUserGroupMemberRequest", + "GetUserGroupRequest", "LinkVerificationState", + "ListAdminAccessBindingsRequest", + "ListAdminAccessBindingsResponse", "ListAnalyticsAccountLinksRequest", "ListAnalyticsAccountLinksResponse", "ListOrganizationsRequest", "ListOrganizationsResponse", + "ListUserGroupMembersRequest", + "ListUserGroupMembersResponse", + "ListUserGroupsRequest", + "ListUserGroupsResponse", "MarketingplatformAdminServiceClient", "Organization", + "OrganizationRole", "ReportPropertyUsageRequest", "ReportPropertyUsageResponse", "SetPropertyServiceLevelRequest", "SetPropertyServiceLevelResponse", + "UpdateAdminAccessBindingRequest", + "UpdateUserGroupMemberRequest", + "UpdateUserGroupRequest", + "UserGroup", + "UserGroupMember", ) api_core.check_python_version("google.ads.marketingplatform_admin_v1alpha") diff --git a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/gapic_metadata.json b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/gapic_metadata.json index 7378e8a813a2..9a7920750266 100644 --- a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/gapic_metadata.json +++ b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/gapic_metadata.json @@ -10,26 +10,71 @@ "grpc": { "libraryClient": "MarketingplatformAdminServiceClient", "rpcs": { + "CreateAdminAccessBinding": { + "methods": [ + "create_admin_access_binding" + ] + }, "CreateAnalyticsAccountLink": { "methods": [ "create_analytics_account_link" ] }, + "CreateUserGroup": { + "methods": [ + "create_user_group" + ] + }, + "CreateUserGroupMember": { + "methods": [ + "create_user_group_member" + ] + }, "DeleteAnalyticsAccountLink": { "methods": [ "delete_analytics_account_link" ] }, + "DeleteUserGroup": { + "methods": [ + "delete_user_group" + ] + }, + "DeleteUserGroupMember": { + "methods": [ + "delete_user_group_member" + ] + }, "FindSalesPartnerManagedClients": { "methods": [ "find_sales_partner_managed_clients" ] }, + "GetAdminAccessBinding": { + "methods": [ + "get_admin_access_binding" + ] + }, "GetOrganization": { "methods": [ "get_organization" ] }, + "GetUserGroup": { + "methods": [ + "get_user_group" + ] + }, + "GetUserGroupMember": { + "methods": [ + "get_user_group_member" + ] + }, + "ListAdminAccessBindings": { + "methods": [ + "list_admin_access_bindings" + ] + }, "ListAnalyticsAccountLinks": { "methods": [ "list_analytics_account_links" @@ -40,6 +85,16 @@ "list_organizations" ] }, + "ListUserGroupMembers": { + "methods": [ + "list_user_group_members" + ] + }, + "ListUserGroups": { + "methods": [ + "list_user_groups" + ] + }, "ReportPropertyUsage": { "methods": [ "report_property_usage" @@ -49,32 +104,92 @@ "methods": [ "set_property_service_level" ] + }, + "UpdateAdminAccessBinding": { + "methods": [ + "update_admin_access_binding" + ] + }, + "UpdateUserGroup": { + "methods": [ + "update_user_group" + ] + }, + "UpdateUserGroupMember": { + "methods": [ + "update_user_group_member" + ] } } }, "grpc-async": { "libraryClient": "MarketingplatformAdminServiceAsyncClient", "rpcs": { + "CreateAdminAccessBinding": { + "methods": [ + "create_admin_access_binding" + ] + }, "CreateAnalyticsAccountLink": { "methods": [ "create_analytics_account_link" ] }, + "CreateUserGroup": { + "methods": [ + "create_user_group" + ] + }, + "CreateUserGroupMember": { + "methods": [ + "create_user_group_member" + ] + }, "DeleteAnalyticsAccountLink": { "methods": [ "delete_analytics_account_link" ] }, + "DeleteUserGroup": { + "methods": [ + "delete_user_group" + ] + }, + "DeleteUserGroupMember": { + "methods": [ + "delete_user_group_member" + ] + }, "FindSalesPartnerManagedClients": { "methods": [ "find_sales_partner_managed_clients" ] }, + "GetAdminAccessBinding": { + "methods": [ + "get_admin_access_binding" + ] + }, "GetOrganization": { "methods": [ "get_organization" ] }, + "GetUserGroup": { + "methods": [ + "get_user_group" + ] + }, + "GetUserGroupMember": { + "methods": [ + "get_user_group_member" + ] + }, + "ListAdminAccessBindings": { + "methods": [ + "list_admin_access_bindings" + ] + }, "ListAnalyticsAccountLinks": { "methods": [ "list_analytics_account_links" @@ -85,6 +200,16 @@ "list_organizations" ] }, + "ListUserGroupMembers": { + "methods": [ + "list_user_group_members" + ] + }, + "ListUserGroups": { + "methods": [ + "list_user_groups" + ] + }, "ReportPropertyUsage": { "methods": [ "report_property_usage" @@ -94,32 +219,92 @@ "methods": [ "set_property_service_level" ] + }, + "UpdateAdminAccessBinding": { + "methods": [ + "update_admin_access_binding" + ] + }, + "UpdateUserGroup": { + "methods": [ + "update_user_group" + ] + }, + "UpdateUserGroupMember": { + "methods": [ + "update_user_group_member" + ] } } }, "rest": { "libraryClient": "MarketingplatformAdminServiceClient", "rpcs": { + "CreateAdminAccessBinding": { + "methods": [ + "create_admin_access_binding" + ] + }, "CreateAnalyticsAccountLink": { "methods": [ "create_analytics_account_link" ] }, + "CreateUserGroup": { + "methods": [ + "create_user_group" + ] + }, + "CreateUserGroupMember": { + "methods": [ + "create_user_group_member" + ] + }, "DeleteAnalyticsAccountLink": { "methods": [ "delete_analytics_account_link" ] }, + "DeleteUserGroup": { + "methods": [ + "delete_user_group" + ] + }, + "DeleteUserGroupMember": { + "methods": [ + "delete_user_group_member" + ] + }, "FindSalesPartnerManagedClients": { "methods": [ "find_sales_partner_managed_clients" ] }, + "GetAdminAccessBinding": { + "methods": [ + "get_admin_access_binding" + ] + }, "GetOrganization": { "methods": [ "get_organization" ] }, + "GetUserGroup": { + "methods": [ + "get_user_group" + ] + }, + "GetUserGroupMember": { + "methods": [ + "get_user_group_member" + ] + }, + "ListAdminAccessBindings": { + "methods": [ + "list_admin_access_bindings" + ] + }, "ListAnalyticsAccountLinks": { "methods": [ "list_analytics_account_links" @@ -130,6 +315,16 @@ "list_organizations" ] }, + "ListUserGroupMembers": { + "methods": [ + "list_user_group_members" + ] + }, + "ListUserGroups": { + "methods": [ + "list_user_groups" + ] + }, "ReportPropertyUsage": { "methods": [ "report_property_usage" @@ -139,6 +334,21 @@ "methods": [ "set_property_service_level" ] + }, + "UpdateAdminAccessBinding": { + "methods": [ + "update_admin_access_binding" + ] + }, + "UpdateUserGroup": { + "methods": [ + "update_user_group" + ] + }, + "UpdateUserGroupMember": { + "methods": [ + "update_user_group_member" + ] } } } diff --git a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/async_client.py b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/async_client.py index 1bedf6b1c83f..e4134279799a 100644 --- a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/async_client.py +++ b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/async_client.py @@ -44,6 +44,8 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore + from google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service import ( pagers, ) @@ -86,6 +88,12 @@ class MarketingplatformAdminServiceAsyncClient: parse_account_path = staticmethod( MarketingplatformAdminServiceClient.parse_account_path ) + admin_access_binding_path = staticmethod( + MarketingplatformAdminServiceClient.admin_access_binding_path + ) + parse_admin_access_binding_path = staticmethod( + MarketingplatformAdminServiceClient.parse_admin_access_binding_path + ) analytics_account_link_path = staticmethod( MarketingplatformAdminServiceClient.analytics_account_link_path ) @@ -102,6 +110,16 @@ class MarketingplatformAdminServiceAsyncClient: parse_property_path = staticmethod( MarketingplatformAdminServiceClient.parse_property_path ) + user_group_path = staticmethod(MarketingplatformAdminServiceClient.user_group_path) + parse_user_group_path = staticmethod( + MarketingplatformAdminServiceClient.parse_user_group_path + ) + user_group_member_path = staticmethod( + MarketingplatformAdminServiceClient.user_group_member_path + ) + parse_user_group_member_path = staticmethod( + MarketingplatformAdminServiceClient.parse_user_group_member_path + ) common_billing_account_path = staticmethod( MarketingplatformAdminServiceClient.common_billing_account_path ) @@ -347,7 +365,7 @@ async def get_organization( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> resources.Organization: - r"""Lookup for a single organization. + r"""Looks up a single organization. .. code-block:: python @@ -1154,7 +1172,7 @@ async def report_property_usage( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> marketingplatform_admin.ReportPropertyUsageResponse: - r"""Get the usage and billing data for properties within + r"""Gets the usage and billing data for properties within the organization for the specified month. Per direct client org, user needs to be @@ -1272,6 +1290,1721 @@ async def sample_report_property_usage(): # Done; return the response. return response + async def get_user_group( + self, + request: Optional[ + Union[marketingplatform_admin.GetUserGroupRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.UserGroup: + r"""Looks up a single user group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + async def sample_get_user_group(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.GetUserGroupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user_group(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ads.marketingplatform_admin_v1alpha.types.GetUserGroupRequest, dict]]): + The request object. Request message for GetUserGroup RPC. + name (:class:`str`): + Required. The name of the UserGroup to retrieve. Format: + organizations/{org_id}/userGroups/{user_group_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.types.UserGroup: + A resource message representing a + user group in a GMP organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, marketingplatform_admin.GetUserGroupRequest): + request = marketingplatform_admin.GetUserGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_user_group + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_user_groups( + self, + request: Optional[ + Union[marketingplatform_admin.ListUserGroupsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListUserGroupsAsyncPager: + r"""Returns a list of user groups in the specified GMP + organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + async def sample_list_user_groups(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.ListUserGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_groups(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupsRequest, dict]]): + The request object. Request message for ListUserGroups + RPC. + parent (:class:`str`): + Required. The parent org where this UserGroup will be + listed. Format: organizations/{org_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListUserGroupsAsyncPager: + Response message for ListUserGroups + RPC. + 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. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, marketingplatform_admin.ListUserGroupsRequest): + request = marketingplatform_admin.ListUserGroupsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_user_groups + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListUserGroupsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_user_group( + self, + request: Optional[ + Union[marketingplatform_admin.CreateUserGroupRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + user_group: Optional[resources.UserGroup] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.UserGroup: + r"""Creates a user group in the specified GMP + organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + async def sample_create_user_group(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.CreateUserGroupRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_user_group(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ads.marketingplatform_admin_v1alpha.types.CreateUserGroupRequest, dict]]): + The request object. Request message for CreateUserGroup + RPC. + parent (:class:`str`): + Required. The parent resource where this UserGroup will + be created. Format: organizations/{org_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_group (:class:`google.ads.marketingplatform_admin_v1alpha.types.UserGroup`): + Required. The user group to create. + This corresponds to the ``user_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.types.UserGroup: + A resource message representing a + user group in a GMP organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, user_group] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, marketingplatform_admin.CreateUserGroupRequest): + request = marketingplatform_admin.CreateUserGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_group is not None: + request.user_group = user_group + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_user_group + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_user_group( + self, + request: Optional[ + Union[marketingplatform_admin.UpdateUserGroupRequest, dict] + ] = None, + *, + user_group: Optional[resources.UserGroup] = 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, Union[str, bytes]]] = (), + ) -> resources.UserGroup: + r"""Updates a user group in the specified GMP + organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + async def sample_update_user_group(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.UpdateUserGroupRequest( + ) + + # Make the request + response = await client.update_user_group(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ads.marketingplatform_admin_v1alpha.types.UpdateUserGroupRequest, dict]]): + The request object. Request message for UpdateUserGroup + RPC. + user_group (:class:`google.ads.marketingplatform_admin_v1alpha.types.UserGroup`): + Required. The user group to update. + This corresponds to the ``user_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to update. Field names must + be in snake case (for example, "field_to_update"). + Omitted fields will not be updated. To replace the + entire entity, use one path with the string "\*" to + match all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.types.UserGroup: + A resource message representing a + user group in a GMP organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [user_group, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, marketingplatform_admin.UpdateUserGroupRequest): + request = marketingplatform_admin.UpdateUserGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user_group is not None: + request.user_group = user_group + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_user_group + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("user_group.name", request.user_group.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_user_group( + self, + request: Optional[ + Union[marketingplatform_admin.DeleteUserGroupRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a user group in the specified GMP + organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + async def sample_delete_user_group(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.DeleteUserGroupRequest( + name="name_value", + ) + + # Make the request + await client.delete_user_group(request=request) + + Args: + request (Optional[Union[google.ads.marketingplatform_admin_v1alpha.types.DeleteUserGroupRequest, dict]]): + The request object. Request message for DeleteUserGroup + RPC. + name (:class:`str`): + Required. The name of the user group to delete. Format: + organizations/{org_id}/userGroups/{user_group_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, marketingplatform_admin.DeleteUserGroupRequest): + request = marketingplatform_admin.DeleteUserGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_user_group + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_user_group_member( + self, + request: Optional[ + Union[marketingplatform_admin.GetUserGroupMemberRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.UserGroupMember: + r"""Looks up a single user group member. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + async def sample_get_user_group_member(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.GetUserGroupMemberRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user_group_member(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ads.marketingplatform_admin_v1alpha.types.GetUserGroupMemberRequest, dict]]): + The request object. Request message for + GetUserGroupMember RPC. + name (:class:`str`): + Required. The name of the user group member to retrieve. + Format: + organizations/{org_id}/userGroups/{user_group_id}/members/{member_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember: + A resource message representing a + member of a user group. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, marketingplatform_admin.GetUserGroupMemberRequest): + request = marketingplatform_admin.GetUserGroupMemberRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_user_group_member + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_user_group_members( + self, + request: Optional[ + Union[marketingplatform_admin.ListUserGroupMembersRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListUserGroupMembersAsyncPager: + r"""Returns a list of members in the specified user + group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + async def sample_list_user_group_members(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.ListUserGroupMembersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_group_members(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupMembersRequest, dict]]): + The request object. Request message for + ListUserGroupMembers RPC. + parent (:class:`str`): + Required. The parent user group where this + UserGroupMember will be listed. Format: + organizations/{org_id}/userGroups/{user_group_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListUserGroupMembersAsyncPager: + Response message for + ListUserGroupMembers RPC. + 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. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, marketingplatform_admin.ListUserGroupMembersRequest): + request = marketingplatform_admin.ListUserGroupMembersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_user_group_members + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListUserGroupMembersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_user_group_member( + self, + request: Optional[ + Union[marketingplatform_admin.CreateUserGroupMemberRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + user_group_member: Optional[resources.UserGroupMember] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.UserGroupMember: + r"""Adds a member to the specified GMP user group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + async def sample_create_user_group_member(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + user_group_member = marketingplatform_admin_v1alpha.UserGroupMember() + user_group_member.user_email = "user_email_value" + + request = marketingplatform_admin_v1alpha.CreateUserGroupMemberRequest( + parent="parent_value", + user_group_member=user_group_member, + ) + + # Make the request + response = await client.create_user_group_member(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ads.marketingplatform_admin_v1alpha.types.CreateUserGroupMemberRequest, dict]]): + The request object. Request message for + CreateUserGroupMember RPC. + parent (:class:`str`): + Required. The parent resource where this UserGroupMember + will be created. Format: + organizations/{org_id}/userGroups/{user_group_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_group_member (:class:`google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember`): + Required. The user group member to + create. + + This corresponds to the ``user_group_member`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember: + A resource message representing a + member of a user group. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, user_group_member] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, marketingplatform_admin.CreateUserGroupMemberRequest + ): + request = marketingplatform_admin.CreateUserGroupMemberRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_group_member is not None: + request.user_group_member = user_group_member + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_user_group_member + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_user_group_member( + self, + request: Optional[ + Union[marketingplatform_admin.UpdateUserGroupMemberRequest, dict] + ] = None, + *, + user_group_member: Optional[resources.UserGroupMember] = 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, Union[str, bytes]]] = (), + ) -> resources.UserGroupMember: + r"""Updates a member in the specified GMP user group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + async def sample_update_user_group_member(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + user_group_member = marketingplatform_admin_v1alpha.UserGroupMember() + user_group_member.user_email = "user_email_value" + + request = marketingplatform_admin_v1alpha.UpdateUserGroupMemberRequest( + user_group_member=user_group_member, + ) + + # Make the request + response = await client.update_user_group_member(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ads.marketingplatform_admin_v1alpha.types.UpdateUserGroupMemberRequest, dict]]): + The request object. Request message for + UpdateUserGroupMember RPC. + user_group_member (:class:`google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember`): + Required. The user group member to + update. + + This corresponds to the ``user_group_member`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to update. Field names must + be in snake case (for example, "field_to_update"). + Omitted fields will not be updated. To replace the + entire entity, use one path with the string "\*" to + match all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember: + A resource message representing a + member of a user group. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [user_group_member, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, marketingplatform_admin.UpdateUserGroupMemberRequest + ): + request = marketingplatform_admin.UpdateUserGroupMemberRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user_group_member is not None: + request.user_group_member = user_group_member + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_user_group_member + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("user_group_member.name", request.user_group_member.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_user_group_member( + self, + request: Optional[ + Union[marketingplatform_admin.DeleteUserGroupMemberRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a member in the specified GMP user group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + async def sample_delete_user_group_member(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.DeleteUserGroupMemberRequest( + name="name_value", + ) + + # Make the request + await client.delete_user_group_member(request=request) + + Args: + request (Optional[Union[google.ads.marketingplatform_admin_v1alpha.types.DeleteUserGroupMemberRequest, dict]]): + The request object. Request message for + DeleteUserGroupMember RPC. + name (:class:`str`): + Required. The name of the user group member to delete. + Format: + organizations/{org_id}/userGroups/{user_group_id}/members/{member_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, marketingplatform_admin.DeleteUserGroupMemberRequest + ): + request = marketingplatform_admin.DeleteUserGroupMemberRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_user_group_member + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_admin_access_binding( + self, + request: Optional[ + Union[marketingplatform_admin.GetAdminAccessBindingRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.AdminAccessBinding: + r"""Looks up a single admin access binding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + async def sample_get_admin_access_binding(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.GetAdminAccessBindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_admin_access_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ads.marketingplatform_admin_v1alpha.types.GetAdminAccessBindingRequest, dict]]): + The request object. Response message for + GetAdminAccessBinding RPC. + name (:class:`str`): + Required. The name of the AdminAccessBinding to + retrieve. Format: + organizations/{org_id}/adminAccessBindings/{admin_access_binding_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding: + A resource message representing a + binding to a set of roles. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, marketingplatform_admin.GetAdminAccessBindingRequest + ): + request = marketingplatform_admin.GetAdminAccessBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_admin_access_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_admin_access_bindings( + self, + request: Optional[ + Union[marketingplatform_admin.ListAdminAccessBindingsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAdminAccessBindingsAsyncPager: + r"""Returns a list of admin access bindings in the + specified GMP organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + async def sample_list_admin_access_bindings(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.ListAdminAccessBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_admin_access_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.ads.marketingplatform_admin_v1alpha.types.ListAdminAccessBindingsRequest, dict]]): + The request object. Request message for + ListAdminAccessBindings RPC. + parent (:class:`str`): + Required. The parent organization, which owns this + collection of Admin Access Bindings. Format: + organizations/{org_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListAdminAccessBindingsAsyncPager: + Response message for + ListAdminAccessBindings RPC. + 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. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, marketingplatform_admin.ListAdminAccessBindingsRequest + ): + request = marketingplatform_admin.ListAdminAccessBindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_admin_access_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAdminAccessBindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_admin_access_binding( + self, + request: Optional[ + Union[marketingplatform_admin.CreateAdminAccessBindingRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + admin_access_binding: Optional[resources.AdminAccessBinding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.AdminAccessBinding: + r"""Creates an admin access binding in the specified GMP + organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + async def sample_create_admin_access_binding(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + admin_access_binding = marketingplatform_admin_v1alpha.AdminAccessBinding() + admin_access_binding.user_email = "user_email_value" + + request = marketingplatform_admin_v1alpha.CreateAdminAccessBindingRequest( + parent="parent_value", + admin_access_binding=admin_access_binding, + ) + + # Make the request + response = await client.create_admin_access_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ads.marketingplatform_admin_v1alpha.types.CreateAdminAccessBindingRequest, dict]]): + The request object. Request message for + CreateAdminAccessBinding RPC. + parent (:class:`str`): + Required. The parent organization, which owns this Admin + Access Binding. Format: organizations/{org_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + admin_access_binding (:class:`google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding`): + Required. The Admin Access Binding to create. + + Only 'user_email' input is allowed. + + This corresponds to the ``admin_access_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding: + A resource message representing a + binding to a set of roles. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, admin_access_binding] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, marketingplatform_admin.CreateAdminAccessBindingRequest + ): + request = marketingplatform_admin.CreateAdminAccessBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if admin_access_binding is not None: + request.admin_access_binding = admin_access_binding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_admin_access_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_admin_access_binding( + self, + request: Optional[ + Union[marketingplatform_admin.UpdateAdminAccessBindingRequest, dict] + ] = None, + *, + admin_access_binding: Optional[resources.AdminAccessBinding] = 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, Union[str, bytes]]] = (), + ) -> resources.AdminAccessBinding: + r"""Updates an admin access binding in the specified GMP + organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + async def sample_update_admin_access_binding(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + admin_access_binding = marketingplatform_admin_v1alpha.AdminAccessBinding() + admin_access_binding.user_email = "user_email_value" + + request = marketingplatform_admin_v1alpha.UpdateAdminAccessBindingRequest( + admin_access_binding=admin_access_binding, + ) + + # Make the request + response = await client.update_admin_access_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ads.marketingplatform_admin_v1alpha.types.UpdateAdminAccessBindingRequest, dict]]): + The request object. Request message for + UpdateAdminAccessBinding RPC. + admin_access_binding (:class:`google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding`): + Required. The AdminAccessBinding to + update. + + This corresponds to the ``admin_access_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to update. Field names must + be in snake case (for example, "field_to_update"). + Omitted fields will not be updated. To replace the + entire entity, use one path with the string "\*" to + match all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding: + A resource message representing a + binding to a set of roles. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [admin_access_binding, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, marketingplatform_admin.UpdateAdminAccessBindingRequest + ): + request = marketingplatform_admin.UpdateAdminAccessBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if admin_access_binding is not None: + request.admin_access_binding = admin_access_binding + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_admin_access_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("admin_access_binding.name", request.admin_access_binding.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self) -> "MarketingplatformAdminServiceAsyncClient": return self diff --git a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/client.py b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/client.py index 3c3383a39e44..af3a65671871 100644 --- a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/client.py +++ b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/client.py @@ -68,6 +68,8 @@ _LOGGER = std_logging.getLogger(__name__) +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore + from google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service import ( pagers, ) @@ -195,6 +197,26 @@ def parse_account_path(path: str) -> Dict[str, str]: m = re.match(r"^accounts/(?P.+?)$", path) return m.groupdict() if m else {} + @staticmethod + def admin_access_binding_path( + organization: str, + admin_access_binding: str, + ) -> str: + """Returns a fully-qualified admin_access_binding string.""" + return "organizations/{organization}/adminAccessBindings/{admin_access_binding}".format( + organization=organization, + admin_access_binding=admin_access_binding, + ) + + @staticmethod + def parse_admin_access_binding_path(path: str) -> Dict[str, str]: + """Parses a admin_access_binding path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/adminAccessBindings/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def analytics_account_link_path( organization: str, @@ -245,6 +267,48 @@ def parse_property_path(path: str) -> Dict[str, str]: m = re.match(r"^properties/(?P.+?)$", path) return m.groupdict() if m else {} + @staticmethod + def user_group_path( + organization: str, + user_group: str, + ) -> str: + """Returns a fully-qualified user_group string.""" + return "organizations/{organization}/userGroups/{user_group}".format( + organization=organization, + user_group=user_group, + ) + + @staticmethod + def parse_user_group_path(path: str) -> Dict[str, str]: + """Parses a user_group path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/userGroups/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def user_group_member_path( + organization: str, + user_group: str, + member: str, + ) -> str: + """Returns a fully-qualified user_group_member string.""" + return "organizations/{organization}/userGroups/{user_group}/members/{member}".format( + organization=organization, + user_group=user_group, + member=member, + ) + + @staticmethod + def parse_user_group_member_path(path: str) -> Dict[str, str]: + """Parses a user_group_member path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/userGroups/(?P.+?)/members/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path( billing_account: str, @@ -666,7 +730,7 @@ def get_organization( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> resources.Organization: - r"""Lookup for a single organization. + r"""Looks up a single organization. .. code-block:: python @@ -1464,7 +1528,7 @@ def report_property_usage( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> marketingplatform_admin.ReportPropertyUsageResponse: - r"""Get the usage and billing data for properties within + r"""Gets the usage and billing data for properties within the organization for the specified month. Per direct client org, user needs to be @@ -1579,6 +1643,1685 @@ def sample_report_property_usage(): # Done; return the response. return response + def get_user_group( + self, + request: Optional[ + Union[marketingplatform_admin.GetUserGroupRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.UserGroup: + r"""Looks up a single user group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + def sample_get_user_group(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.GetUserGroupRequest( + name="name_value", + ) + + # Make the request + response = client.get_user_group(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.marketingplatform_admin_v1alpha.types.GetUserGroupRequest, dict]): + The request object. Request message for GetUserGroup RPC. + name (str): + Required. The name of the UserGroup to retrieve. Format: + organizations/{org_id}/userGroups/{user_group_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.types.UserGroup: + A resource message representing a + user group in a GMP organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, marketingplatform_admin.GetUserGroupRequest): + request = marketingplatform_admin.GetUserGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_user_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_user_groups( + self, + request: Optional[ + Union[marketingplatform_admin.ListUserGroupsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListUserGroupsPager: + r"""Returns a list of user groups in the specified GMP + organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + def sample_list_user_groups(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.ListUserGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_groups(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupsRequest, dict]): + The request object. Request message for ListUserGroups + RPC. + parent (str): + Required. The parent org where this UserGroup will be + listed. Format: organizations/{org_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListUserGroupsPager: + Response message for ListUserGroups + RPC. + 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. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, marketingplatform_admin.ListUserGroupsRequest): + request = marketingplatform_admin.ListUserGroupsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_user_groups] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListUserGroupsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_user_group( + self, + request: Optional[ + Union[marketingplatform_admin.CreateUserGroupRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + user_group: Optional[resources.UserGroup] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.UserGroup: + r"""Creates a user group in the specified GMP + organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + def sample_create_user_group(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.CreateUserGroupRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_user_group(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.marketingplatform_admin_v1alpha.types.CreateUserGroupRequest, dict]): + The request object. Request message for CreateUserGroup + RPC. + parent (str): + Required. The parent resource where this UserGroup will + be created. Format: organizations/{org_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_group (google.ads.marketingplatform_admin_v1alpha.types.UserGroup): + Required. The user group to create. + This corresponds to the ``user_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.types.UserGroup: + A resource message representing a + user group in a GMP organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, user_group] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, marketingplatform_admin.CreateUserGroupRequest): + request = marketingplatform_admin.CreateUserGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_group is not None: + request.user_group = user_group + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_user_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_user_group( + self, + request: Optional[ + Union[marketingplatform_admin.UpdateUserGroupRequest, dict] + ] = None, + *, + user_group: Optional[resources.UserGroup] = 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, Union[str, bytes]]] = (), + ) -> resources.UserGroup: + r"""Updates a user group in the specified GMP + organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + def sample_update_user_group(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.UpdateUserGroupRequest( + ) + + # Make the request + response = client.update_user_group(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.marketingplatform_admin_v1alpha.types.UpdateUserGroupRequest, dict]): + The request object. Request message for UpdateUserGroup + RPC. + user_group (google.ads.marketingplatform_admin_v1alpha.types.UserGroup): + Required. The user group to update. + This corresponds to the ``user_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. Field names must + be in snake case (for example, "field_to_update"). + Omitted fields will not be updated. To replace the + entire entity, use one path with the string "\*" to + match all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.types.UserGroup: + A resource message representing a + user group in a GMP organization. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [user_group, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, marketingplatform_admin.UpdateUserGroupRequest): + request = marketingplatform_admin.UpdateUserGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user_group is not None: + request.user_group = user_group + 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_user_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("user_group.name", request.user_group.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_user_group( + self, + request: Optional[ + Union[marketingplatform_admin.DeleteUserGroupRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a user group in the specified GMP + organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + def sample_delete_user_group(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.DeleteUserGroupRequest( + name="name_value", + ) + + # Make the request + client.delete_user_group(request=request) + + Args: + request (Union[google.ads.marketingplatform_admin_v1alpha.types.DeleteUserGroupRequest, dict]): + The request object. Request message for DeleteUserGroup + RPC. + name (str): + Required. The name of the user group to delete. Format: + organizations/{org_id}/userGroups/{user_group_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, marketingplatform_admin.DeleteUserGroupRequest): + request = marketingplatform_admin.DeleteUserGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_user_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_user_group_member( + self, + request: Optional[ + Union[marketingplatform_admin.GetUserGroupMemberRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.UserGroupMember: + r"""Looks up a single user group member. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + def sample_get_user_group_member(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.GetUserGroupMemberRequest( + name="name_value", + ) + + # Make the request + response = client.get_user_group_member(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.marketingplatform_admin_v1alpha.types.GetUserGroupMemberRequest, dict]): + The request object. Request message for + GetUserGroupMember RPC. + name (str): + Required. The name of the user group member to retrieve. + Format: + organizations/{org_id}/userGroups/{user_group_id}/members/{member_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember: + A resource message representing a + member of a user group. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, marketingplatform_admin.GetUserGroupMemberRequest): + request = marketingplatform_admin.GetUserGroupMemberRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_user_group_member] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_user_group_members( + self, + request: Optional[ + Union[marketingplatform_admin.ListUserGroupMembersRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListUserGroupMembersPager: + r"""Returns a list of members in the specified user + group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + def sample_list_user_group_members(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.ListUserGroupMembersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_group_members(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupMembersRequest, dict]): + The request object. Request message for + ListUserGroupMembers RPC. + parent (str): + Required. The parent user group where this + UserGroupMember will be listed. Format: + organizations/{org_id}/userGroups/{user_group_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListUserGroupMembersPager: + Response message for + ListUserGroupMembers RPC. + 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. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, marketingplatform_admin.ListUserGroupMembersRequest): + request = marketingplatform_admin.ListUserGroupMembersRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_user_group_members] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListUserGroupMembersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_user_group_member( + self, + request: Optional[ + Union[marketingplatform_admin.CreateUserGroupMemberRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + user_group_member: Optional[resources.UserGroupMember] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.UserGroupMember: + r"""Adds a member to the specified GMP user group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + def sample_create_user_group_member(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + user_group_member = marketingplatform_admin_v1alpha.UserGroupMember() + user_group_member.user_email = "user_email_value" + + request = marketingplatform_admin_v1alpha.CreateUserGroupMemberRequest( + parent="parent_value", + user_group_member=user_group_member, + ) + + # Make the request + response = client.create_user_group_member(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.marketingplatform_admin_v1alpha.types.CreateUserGroupMemberRequest, dict]): + The request object. Request message for + CreateUserGroupMember RPC. + parent (str): + Required. The parent resource where this UserGroupMember + will be created. Format: + organizations/{org_id}/userGroups/{user_group_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_group_member (google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember): + Required. The user group member to + create. + + This corresponds to the ``user_group_member`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember: + A resource message representing a + member of a user group. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, user_group_member] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, marketingplatform_admin.CreateUserGroupMemberRequest + ): + request = marketingplatform_admin.CreateUserGroupMemberRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_group_member is not None: + request.user_group_member = user_group_member + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_user_group_member] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_user_group_member( + self, + request: Optional[ + Union[marketingplatform_admin.UpdateUserGroupMemberRequest, dict] + ] = None, + *, + user_group_member: Optional[resources.UserGroupMember] = 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, Union[str, bytes]]] = (), + ) -> resources.UserGroupMember: + r"""Updates a member in the specified GMP user group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + def sample_update_user_group_member(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + user_group_member = marketingplatform_admin_v1alpha.UserGroupMember() + user_group_member.user_email = "user_email_value" + + request = marketingplatform_admin_v1alpha.UpdateUserGroupMemberRequest( + user_group_member=user_group_member, + ) + + # Make the request + response = client.update_user_group_member(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.marketingplatform_admin_v1alpha.types.UpdateUserGroupMemberRequest, dict]): + The request object. Request message for + UpdateUserGroupMember RPC. + user_group_member (google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember): + Required. The user group member to + update. + + This corresponds to the ``user_group_member`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. Field names must + be in snake case (for example, "field_to_update"). + Omitted fields will not be updated. To replace the + entire entity, use one path with the string "\*" to + match all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember: + A resource message representing a + member of a user group. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [user_group_member, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, marketingplatform_admin.UpdateUserGroupMemberRequest + ): + request = marketingplatform_admin.UpdateUserGroupMemberRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user_group_member is not None: + request.user_group_member = user_group_member + 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_user_group_member] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("user_group_member.name", request.user_group_member.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_user_group_member( + self, + request: Optional[ + Union[marketingplatform_admin.DeleteUserGroupMemberRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a member in the specified GMP user group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + def sample_delete_user_group_member(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.DeleteUserGroupMemberRequest( + name="name_value", + ) + + # Make the request + client.delete_user_group_member(request=request) + + Args: + request (Union[google.ads.marketingplatform_admin_v1alpha.types.DeleteUserGroupMemberRequest, dict]): + The request object. Request message for + DeleteUserGroupMember RPC. + name (str): + Required. The name of the user group member to delete. + Format: + organizations/{org_id}/userGroups/{user_group_id}/members/{member_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, marketingplatform_admin.DeleteUserGroupMemberRequest + ): + request = marketingplatform_admin.DeleteUserGroupMemberRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_user_group_member] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_admin_access_binding( + self, + request: Optional[ + Union[marketingplatform_admin.GetAdminAccessBindingRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.AdminAccessBinding: + r"""Looks up a single admin access binding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + def sample_get_admin_access_binding(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.GetAdminAccessBindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_admin_access_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.marketingplatform_admin_v1alpha.types.GetAdminAccessBindingRequest, dict]): + The request object. Response message for + GetAdminAccessBinding RPC. + name (str): + Required. The name of the AdminAccessBinding to + retrieve. Format: + organizations/{org_id}/adminAccessBindings/{admin_access_binding_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding: + A resource message representing a + binding to a set of roles. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, marketingplatform_admin.GetAdminAccessBindingRequest + ): + request = marketingplatform_admin.GetAdminAccessBindingRequest(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_admin_access_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_admin_access_bindings( + self, + request: Optional[ + Union[marketingplatform_admin.ListAdminAccessBindingsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAdminAccessBindingsPager: + r"""Returns a list of admin access bindings in the + specified GMP organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + def sample_list_admin_access_bindings(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.ListAdminAccessBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_admin_access_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.ads.marketingplatform_admin_v1alpha.types.ListAdminAccessBindingsRequest, dict]): + The request object. Request message for + ListAdminAccessBindings RPC. + parent (str): + Required. The parent organization, which owns this + collection of Admin Access Bindings. Format: + organizations/{org_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListAdminAccessBindingsPager: + Response message for + ListAdminAccessBindings RPC. + 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. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, marketingplatform_admin.ListAdminAccessBindingsRequest + ): + request = marketingplatform_admin.ListAdminAccessBindingsRequest(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_admin_access_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAdminAccessBindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_admin_access_binding( + self, + request: Optional[ + Union[marketingplatform_admin.CreateAdminAccessBindingRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + admin_access_binding: Optional[resources.AdminAccessBinding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.AdminAccessBinding: + r"""Creates an admin access binding in the specified GMP + organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + def sample_create_admin_access_binding(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + admin_access_binding = marketingplatform_admin_v1alpha.AdminAccessBinding() + admin_access_binding.user_email = "user_email_value" + + request = marketingplatform_admin_v1alpha.CreateAdminAccessBindingRequest( + parent="parent_value", + admin_access_binding=admin_access_binding, + ) + + # Make the request + response = client.create_admin_access_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.marketingplatform_admin_v1alpha.types.CreateAdminAccessBindingRequest, dict]): + The request object. Request message for + CreateAdminAccessBinding RPC. + parent (str): + Required. The parent organization, which owns this Admin + Access Binding. Format: organizations/{org_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + admin_access_binding (google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding): + Required. The Admin Access Binding to create. + + Only 'user_email' input is allowed. + + This corresponds to the ``admin_access_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding: + A resource message representing a + binding to a set of roles. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, admin_access_binding] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, marketingplatform_admin.CreateAdminAccessBindingRequest + ): + request = marketingplatform_admin.CreateAdminAccessBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if admin_access_binding is not None: + request.admin_access_binding = admin_access_binding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_admin_access_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_admin_access_binding( + self, + request: Optional[ + Union[marketingplatform_admin.UpdateAdminAccessBindingRequest, dict] + ] = None, + *, + admin_access_binding: Optional[resources.AdminAccessBinding] = 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, Union[str, bytes]]] = (), + ) -> resources.AdminAccessBinding: + r"""Updates an admin access binding in the specified GMP + organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import marketingplatform_admin_v1alpha + + def sample_update_admin_access_binding(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + admin_access_binding = marketingplatform_admin_v1alpha.AdminAccessBinding() + admin_access_binding.user_email = "user_email_value" + + request = marketingplatform_admin_v1alpha.UpdateAdminAccessBindingRequest( + admin_access_binding=admin_access_binding, + ) + + # Make the request + response = client.update_admin_access_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.marketingplatform_admin_v1alpha.types.UpdateAdminAccessBindingRequest, dict]): + The request object. Request message for + UpdateAdminAccessBinding RPC. + admin_access_binding (google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding): + Required. The AdminAccessBinding to + update. + + This corresponds to the ``admin_access_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. Field names must + be in snake case (for example, "field_to_update"). + Omitted fields will not be updated. To replace the + entire entity, use one path with the string "\*" to + match all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding: + A resource message representing a + binding to a set of roles. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [admin_access_binding, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, marketingplatform_admin.UpdateAdminAccessBindingRequest + ): + request = marketingplatform_admin.UpdateAdminAccessBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if admin_access_binding is not None: + request.admin_access_binding = admin_access_binding + 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_admin_access_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("admin_access_binding.name", request.admin_access_binding.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "MarketingplatformAdminServiceClient": return self diff --git a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/pagers.py b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/pagers.py index 71251703fbd3..f9cf33bdb5b1 100644 --- a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/pagers.py +++ b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/pagers.py @@ -370,3 +370,485 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListUserGroupsPager: + """A pager for iterating through ``list_user_groups`` requests. + + This class thinly wraps an initial + :class:`google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``user_groups`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUserGroups`` requests and continue to iterate + through the ``user_groups`` field on the + corresponding responses. + + All the usual :class:`google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupsResponse` + 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[..., marketingplatform_admin.ListUserGroupsResponse], + request: marketingplatform_admin.ListUserGroupsRequest, + response: marketingplatform_admin.ListUserGroupsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupsRequest): + The initial request object. + response (google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = marketingplatform_admin.ListUserGroupsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[marketingplatform_admin.ListUserGroupsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[resources.UserGroup]: + for page in self.pages: + yield from page.user_groups + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListUserGroupsAsyncPager: + """A pager for iterating through ``list_user_groups`` requests. + + This class thinly wraps an initial + :class:`google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``user_groups`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUserGroups`` requests and continue to iterate + through the ``user_groups`` field on the + corresponding responses. + + All the usual :class:`google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupsResponse` + 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[marketingplatform_admin.ListUserGroupsResponse] + ], + request: marketingplatform_admin.ListUserGroupsRequest, + response: marketingplatform_admin.ListUserGroupsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupsRequest): + The initial request object. + response (google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = marketingplatform_admin.ListUserGroupsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[marketingplatform_admin.ListUserGroupsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[resources.UserGroup]: + async def async_generator(): + async for page in self.pages: + for response in page.user_groups: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListUserGroupMembersPager: + """A pager for iterating through ``list_user_group_members`` requests. + + This class thinly wraps an initial + :class:`google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupMembersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``user_group_members`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUserGroupMembers`` requests and continue to iterate + through the ``user_group_members`` field on the + corresponding responses. + + All the usual :class:`google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupMembersResponse` + 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[..., marketingplatform_admin.ListUserGroupMembersResponse], + request: marketingplatform_admin.ListUserGroupMembersRequest, + response: marketingplatform_admin.ListUserGroupMembersResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupMembersRequest): + The initial request object. + response (google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupMembersResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = marketingplatform_admin.ListUserGroupMembersRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[marketingplatform_admin.ListUserGroupMembersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[resources.UserGroupMember]: + for page in self.pages: + yield from page.user_group_members + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListUserGroupMembersAsyncPager: + """A pager for iterating through ``list_user_group_members`` requests. + + This class thinly wraps an initial + :class:`google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupMembersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``user_group_members`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUserGroupMembers`` requests and continue to iterate + through the ``user_group_members`` field on the + corresponding responses. + + All the usual :class:`google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupMembersResponse` + 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[marketingplatform_admin.ListUserGroupMembersResponse] + ], + request: marketingplatform_admin.ListUserGroupMembersRequest, + response: marketingplatform_admin.ListUserGroupMembersResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupMembersRequest): + The initial request object. + response (google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupMembersResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = marketingplatform_admin.ListUserGroupMembersRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[marketingplatform_admin.ListUserGroupMembersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[resources.UserGroupMember]: + async def async_generator(): + async for page in self.pages: + for response in page.user_group_members: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAdminAccessBindingsPager: + """A pager for iterating through ``list_admin_access_bindings`` requests. + + This class thinly wraps an initial + :class:`google.ads.marketingplatform_admin_v1alpha.types.ListAdminAccessBindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``admin_access_bindings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAdminAccessBindings`` requests and continue to iterate + through the ``admin_access_bindings`` field on the + corresponding responses. + + All the usual :class:`google.ads.marketingplatform_admin_v1alpha.types.ListAdminAccessBindingsResponse` + 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[..., marketingplatform_admin.ListAdminAccessBindingsResponse], + request: marketingplatform_admin.ListAdminAccessBindingsRequest, + response: marketingplatform_admin.ListAdminAccessBindingsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.ads.marketingplatform_admin_v1alpha.types.ListAdminAccessBindingsRequest): + The initial request object. + response (google.ads.marketingplatform_admin_v1alpha.types.ListAdminAccessBindingsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = marketingplatform_admin.ListAdminAccessBindingsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[marketingplatform_admin.ListAdminAccessBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[resources.AdminAccessBinding]: + for page in self.pages: + yield from page.admin_access_bindings + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAdminAccessBindingsAsyncPager: + """A pager for iterating through ``list_admin_access_bindings`` requests. + + This class thinly wraps an initial + :class:`google.ads.marketingplatform_admin_v1alpha.types.ListAdminAccessBindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``admin_access_bindings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAdminAccessBindings`` requests and continue to iterate + through the ``admin_access_bindings`` field on the + corresponding responses. + + All the usual :class:`google.ads.marketingplatform_admin_v1alpha.types.ListAdminAccessBindingsResponse` + 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[marketingplatform_admin.ListAdminAccessBindingsResponse] + ], + request: marketingplatform_admin.ListAdminAccessBindingsRequest, + response: marketingplatform_admin.ListAdminAccessBindingsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.ads.marketingplatform_admin_v1alpha.types.ListAdminAccessBindingsRequest): + The initial request object. + response (google.ads.marketingplatform_admin_v1alpha.types.ListAdminAccessBindingsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = marketingplatform_admin.ListAdminAccessBindingsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[marketingplatform_admin.ListAdminAccessBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[resources.AdminAccessBinding]: + async def async_generator(): + async for page in self.pages: + for response in page.admin_access_bindings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/base.py b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/base.py index 1ad112e09318..ba0fd58d93fe 100644 --- a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/base.py +++ b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/base.py @@ -187,6 +187,76 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_user_group: gapic_v1.method.wrap_method( + self.get_user_group, + default_timeout=None, + client_info=client_info, + ), + self.list_user_groups: gapic_v1.method.wrap_method( + self.list_user_groups, + default_timeout=None, + client_info=client_info, + ), + self.create_user_group: gapic_v1.method.wrap_method( + self.create_user_group, + default_timeout=None, + client_info=client_info, + ), + self.update_user_group: gapic_v1.method.wrap_method( + self.update_user_group, + default_timeout=None, + client_info=client_info, + ), + self.delete_user_group: gapic_v1.method.wrap_method( + self.delete_user_group, + default_timeout=None, + client_info=client_info, + ), + self.get_user_group_member: gapic_v1.method.wrap_method( + self.get_user_group_member, + default_timeout=None, + client_info=client_info, + ), + self.list_user_group_members: gapic_v1.method.wrap_method( + self.list_user_group_members, + default_timeout=None, + client_info=client_info, + ), + self.create_user_group_member: gapic_v1.method.wrap_method( + self.create_user_group_member, + default_timeout=None, + client_info=client_info, + ), + self.update_user_group_member: gapic_v1.method.wrap_method( + self.update_user_group_member, + default_timeout=None, + client_info=client_info, + ), + self.delete_user_group_member: gapic_v1.method.wrap_method( + self.delete_user_group_member, + default_timeout=None, + client_info=client_info, + ), + self.get_admin_access_binding: gapic_v1.method.wrap_method( + self.get_admin_access_binding, + default_timeout=None, + client_info=client_info, + ), + self.list_admin_access_bindings: gapic_v1.method.wrap_method( + self.list_admin_access_bindings, + default_timeout=None, + client_info=client_info, + ), + self.create_admin_access_binding: gapic_v1.method.wrap_method( + self.create_admin_access_binding, + default_timeout=None, + client_info=client_info, + ), + self.update_admin_access_binding: gapic_v1.method.wrap_method( + self.update_admin_access_binding, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -287,6 +357,141 @@ def report_property_usage( ]: raise NotImplementedError() + @property + def get_user_group( + self, + ) -> Callable[ + [marketingplatform_admin.GetUserGroupRequest], + Union[resources.UserGroup, Awaitable[resources.UserGroup]], + ]: + raise NotImplementedError() + + @property + def list_user_groups( + self, + ) -> Callable[ + [marketingplatform_admin.ListUserGroupsRequest], + Union[ + marketingplatform_admin.ListUserGroupsResponse, + Awaitable[marketingplatform_admin.ListUserGroupsResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_user_group( + self, + ) -> Callable[ + [marketingplatform_admin.CreateUserGroupRequest], + Union[resources.UserGroup, Awaitable[resources.UserGroup]], + ]: + raise NotImplementedError() + + @property + def update_user_group( + self, + ) -> Callable[ + [marketingplatform_admin.UpdateUserGroupRequest], + Union[resources.UserGroup, Awaitable[resources.UserGroup]], + ]: + raise NotImplementedError() + + @property + def delete_user_group( + self, + ) -> Callable[ + [marketingplatform_admin.DeleteUserGroupRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def get_user_group_member( + self, + ) -> Callable[ + [marketingplatform_admin.GetUserGroupMemberRequest], + Union[resources.UserGroupMember, Awaitable[resources.UserGroupMember]], + ]: + raise NotImplementedError() + + @property + def list_user_group_members( + self, + ) -> Callable[ + [marketingplatform_admin.ListUserGroupMembersRequest], + Union[ + marketingplatform_admin.ListUserGroupMembersResponse, + Awaitable[marketingplatform_admin.ListUserGroupMembersResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_user_group_member( + self, + ) -> Callable[ + [marketingplatform_admin.CreateUserGroupMemberRequest], + Union[resources.UserGroupMember, Awaitable[resources.UserGroupMember]], + ]: + raise NotImplementedError() + + @property + def update_user_group_member( + self, + ) -> Callable[ + [marketingplatform_admin.UpdateUserGroupMemberRequest], + Union[resources.UserGroupMember, Awaitable[resources.UserGroupMember]], + ]: + raise NotImplementedError() + + @property + def delete_user_group_member( + self, + ) -> Callable[ + [marketingplatform_admin.DeleteUserGroupMemberRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def get_admin_access_binding( + self, + ) -> Callable[ + [marketingplatform_admin.GetAdminAccessBindingRequest], + Union[resources.AdminAccessBinding, Awaitable[resources.AdminAccessBinding]], + ]: + raise NotImplementedError() + + @property + def list_admin_access_bindings( + self, + ) -> Callable[ + [marketingplatform_admin.ListAdminAccessBindingsRequest], + Union[ + marketingplatform_admin.ListAdminAccessBindingsResponse, + Awaitable[marketingplatform_admin.ListAdminAccessBindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_admin_access_binding( + self, + ) -> Callable[ + [marketingplatform_admin.CreateAdminAccessBindingRequest], + Union[resources.AdminAccessBinding, Awaitable[resources.AdminAccessBinding]], + ]: + raise NotImplementedError() + + @property + def update_admin_access_binding( + self, + ) -> Callable[ + [marketingplatform_admin.UpdateAdminAccessBindingRequest], + Union[resources.AdminAccessBinding, Awaitable[resources.AdminAccessBinding]], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/grpc.py b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/grpc.py index 862ce0a4f83b..63ed455ddc26 100644 --- a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/grpc.py +++ b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/grpc.py @@ -340,7 +340,7 @@ def get_organization( ]: r"""Return a callable for the get organization method over gRPC. - Lookup for a single organization. + Looks up a single organization. Returns: Callable[[~.GetOrganizationRequest], @@ -570,7 +570,7 @@ def report_property_usage( ]: r"""Return a callable for the report property usage method over gRPC. - Get the usage and billing data for properties within + Gets the usage and billing data for properties within the organization for the specified month. Per direct client org, user needs to be @@ -601,6 +601,416 @@ def report_property_usage( ) return self._stubs["report_property_usage"] + @property + def get_user_group( + self, + ) -> Callable[[marketingplatform_admin.GetUserGroupRequest], resources.UserGroup]: + r"""Return a callable for the get user group method over gRPC. + + Looks up a single user group. + + Returns: + Callable[[~.GetUserGroupRequest], + ~.UserGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_user_group" not in self._stubs: + self._stubs["get_user_group"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/GetUserGroup", + request_serializer=marketingplatform_admin.GetUserGroupRequest.serialize, + response_deserializer=resources.UserGroup.deserialize, + ) + return self._stubs["get_user_group"] + + @property + def list_user_groups( + self, + ) -> Callable[ + [marketingplatform_admin.ListUserGroupsRequest], + marketingplatform_admin.ListUserGroupsResponse, + ]: + r"""Return a callable for the list user groups method over gRPC. + + Returns a list of user groups in the specified GMP + organization. + + Returns: + Callable[[~.ListUserGroupsRequest], + ~.ListUserGroupsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_user_groups" not in self._stubs: + self._stubs["list_user_groups"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/ListUserGroups", + request_serializer=marketingplatform_admin.ListUserGroupsRequest.serialize, + response_deserializer=marketingplatform_admin.ListUserGroupsResponse.deserialize, + ) + return self._stubs["list_user_groups"] + + @property + def create_user_group( + self, + ) -> Callable[ + [marketingplatform_admin.CreateUserGroupRequest], resources.UserGroup + ]: + r"""Return a callable for the create user group method over gRPC. + + Creates a user group in the specified GMP + organization. + + Returns: + Callable[[~.CreateUserGroupRequest], + ~.UserGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_user_group" not in self._stubs: + self._stubs["create_user_group"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/CreateUserGroup", + request_serializer=marketingplatform_admin.CreateUserGroupRequest.serialize, + response_deserializer=resources.UserGroup.deserialize, + ) + return self._stubs["create_user_group"] + + @property + def update_user_group( + self, + ) -> Callable[ + [marketingplatform_admin.UpdateUserGroupRequest], resources.UserGroup + ]: + r"""Return a callable for the update user group method over gRPC. + + Updates a user group in the specified GMP + organization. + + Returns: + Callable[[~.UpdateUserGroupRequest], + ~.UserGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_user_group" not in self._stubs: + self._stubs["update_user_group"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/UpdateUserGroup", + request_serializer=marketingplatform_admin.UpdateUserGroupRequest.serialize, + response_deserializer=resources.UserGroup.deserialize, + ) + return self._stubs["update_user_group"] + + @property + def delete_user_group( + self, + ) -> Callable[[marketingplatform_admin.DeleteUserGroupRequest], empty_pb2.Empty]: + r"""Return a callable for the delete user group method over gRPC. + + Deletes a user group in the specified GMP + organization. + + Returns: + Callable[[~.DeleteUserGroupRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_user_group" not in self._stubs: + self._stubs["delete_user_group"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/DeleteUserGroup", + request_serializer=marketingplatform_admin.DeleteUserGroupRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_user_group"] + + @property + def get_user_group_member( + self, + ) -> Callable[ + [marketingplatform_admin.GetUserGroupMemberRequest], resources.UserGroupMember + ]: + r"""Return a callable for the get user group member method over gRPC. + + Looks up a single user group member. + + Returns: + Callable[[~.GetUserGroupMemberRequest], + ~.UserGroupMember]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_user_group_member" not in self._stubs: + self._stubs["get_user_group_member"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/GetUserGroupMember", + request_serializer=marketingplatform_admin.GetUserGroupMemberRequest.serialize, + response_deserializer=resources.UserGroupMember.deserialize, + ) + return self._stubs["get_user_group_member"] + + @property + def list_user_group_members( + self, + ) -> Callable[ + [marketingplatform_admin.ListUserGroupMembersRequest], + marketingplatform_admin.ListUserGroupMembersResponse, + ]: + r"""Return a callable for the list user group members method over gRPC. + + Returns a list of members in the specified user + group. + + Returns: + Callable[[~.ListUserGroupMembersRequest], + ~.ListUserGroupMembersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_user_group_members" not in self._stubs: + self._stubs["list_user_group_members"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/ListUserGroupMembers", + request_serializer=marketingplatform_admin.ListUserGroupMembersRequest.serialize, + response_deserializer=marketingplatform_admin.ListUserGroupMembersResponse.deserialize, + ) + return self._stubs["list_user_group_members"] + + @property + def create_user_group_member( + self, + ) -> Callable[ + [marketingplatform_admin.CreateUserGroupMemberRequest], + resources.UserGroupMember, + ]: + r"""Return a callable for the create user group member method over gRPC. + + Adds a member to the specified GMP user group. + + Returns: + Callable[[~.CreateUserGroupMemberRequest], + ~.UserGroupMember]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_user_group_member" not in self._stubs: + self._stubs["create_user_group_member"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/CreateUserGroupMember", + request_serializer=marketingplatform_admin.CreateUserGroupMemberRequest.serialize, + response_deserializer=resources.UserGroupMember.deserialize, + ) + return self._stubs["create_user_group_member"] + + @property + def update_user_group_member( + self, + ) -> Callable[ + [marketingplatform_admin.UpdateUserGroupMemberRequest], + resources.UserGroupMember, + ]: + r"""Return a callable for the update user group member method over gRPC. + + Updates a member in the specified GMP user group. + + Returns: + Callable[[~.UpdateUserGroupMemberRequest], + ~.UserGroupMember]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_user_group_member" not in self._stubs: + self._stubs["update_user_group_member"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/UpdateUserGroupMember", + request_serializer=marketingplatform_admin.UpdateUserGroupMemberRequest.serialize, + response_deserializer=resources.UserGroupMember.deserialize, + ) + return self._stubs["update_user_group_member"] + + @property + def delete_user_group_member( + self, + ) -> Callable[ + [marketingplatform_admin.DeleteUserGroupMemberRequest], empty_pb2.Empty + ]: + r"""Return a callable for the delete user group member method over gRPC. + + Deletes a member in the specified GMP user group. + + Returns: + Callable[[~.DeleteUserGroupMemberRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_user_group_member" not in self._stubs: + self._stubs["delete_user_group_member"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/DeleteUserGroupMember", + request_serializer=marketingplatform_admin.DeleteUserGroupMemberRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_user_group_member"] + + @property + def get_admin_access_binding( + self, + ) -> Callable[ + [marketingplatform_admin.GetAdminAccessBindingRequest], + resources.AdminAccessBinding, + ]: + r"""Return a callable for the get admin access binding method over gRPC. + + Looks up a single admin access binding. + + Returns: + Callable[[~.GetAdminAccessBindingRequest], + ~.AdminAccessBinding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_admin_access_binding" not in self._stubs: + self._stubs["get_admin_access_binding"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/GetAdminAccessBinding", + request_serializer=marketingplatform_admin.GetAdminAccessBindingRequest.serialize, + response_deserializer=resources.AdminAccessBinding.deserialize, + ) + return self._stubs["get_admin_access_binding"] + + @property + def list_admin_access_bindings( + self, + ) -> Callable[ + [marketingplatform_admin.ListAdminAccessBindingsRequest], + marketingplatform_admin.ListAdminAccessBindingsResponse, + ]: + r"""Return a callable for the list admin access bindings method over gRPC. + + Returns a list of admin access bindings in the + specified GMP organization. + + Returns: + Callable[[~.ListAdminAccessBindingsRequest], + ~.ListAdminAccessBindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_admin_access_bindings" not in self._stubs: + self._stubs["list_admin_access_bindings"] = ( + self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/ListAdminAccessBindings", + request_serializer=marketingplatform_admin.ListAdminAccessBindingsRequest.serialize, + response_deserializer=marketingplatform_admin.ListAdminAccessBindingsResponse.deserialize, + ) + ) + return self._stubs["list_admin_access_bindings"] + + @property + def create_admin_access_binding( + self, + ) -> Callable[ + [marketingplatform_admin.CreateAdminAccessBindingRequest], + resources.AdminAccessBinding, + ]: + r"""Return a callable for the create admin access binding method over gRPC. + + Creates an admin access binding in the specified GMP + organization. + + Returns: + Callable[[~.CreateAdminAccessBindingRequest], + ~.AdminAccessBinding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_admin_access_binding" not in self._stubs: + self._stubs["create_admin_access_binding"] = ( + self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/CreateAdminAccessBinding", + request_serializer=marketingplatform_admin.CreateAdminAccessBindingRequest.serialize, + response_deserializer=resources.AdminAccessBinding.deserialize, + ) + ) + return self._stubs["create_admin_access_binding"] + + @property + def update_admin_access_binding( + self, + ) -> Callable[ + [marketingplatform_admin.UpdateAdminAccessBindingRequest], + resources.AdminAccessBinding, + ]: + r"""Return a callable for the update admin access binding method over gRPC. + + Updates an admin access binding in the specified GMP + organization. + + Returns: + Callable[[~.UpdateAdminAccessBindingRequest], + ~.AdminAccessBinding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_admin_access_binding" not in self._stubs: + self._stubs["update_admin_access_binding"] = ( + self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/UpdateAdminAccessBinding", + request_serializer=marketingplatform_admin.UpdateAdminAccessBindingRequest.serialize, + response_deserializer=resources.AdminAccessBinding.deserialize, + ) + ) + return self._stubs["update_admin_access_binding"] + def close(self): self._logged_channel.close() diff --git a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/grpc_asyncio.py b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/grpc_asyncio.py index 636f87c3a01c..c6ad0820e780 100644 --- a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/grpc_asyncio.py +++ b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/grpc_asyncio.py @@ -349,7 +349,7 @@ def get_organization( ]: r"""Return a callable for the get organization method over gRPC. - Lookup for a single organization. + Looks up a single organization. Returns: Callable[[~.GetOrganizationRequest], @@ -580,7 +580,7 @@ def report_property_usage( ]: r"""Return a callable for the report property usage method over gRPC. - Get the usage and billing data for properties within + Gets the usage and billing data for properties within the organization for the specified month. Per direct client org, user needs to be @@ -611,6 +611,422 @@ def report_property_usage( ) return self._stubs["report_property_usage"] + @property + def get_user_group( + self, + ) -> Callable[ + [marketingplatform_admin.GetUserGroupRequest], Awaitable[resources.UserGroup] + ]: + r"""Return a callable for the get user group method over gRPC. + + Looks up a single user group. + + Returns: + Callable[[~.GetUserGroupRequest], + Awaitable[~.UserGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_user_group" not in self._stubs: + self._stubs["get_user_group"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/GetUserGroup", + request_serializer=marketingplatform_admin.GetUserGroupRequest.serialize, + response_deserializer=resources.UserGroup.deserialize, + ) + return self._stubs["get_user_group"] + + @property + def list_user_groups( + self, + ) -> Callable[ + [marketingplatform_admin.ListUserGroupsRequest], + Awaitable[marketingplatform_admin.ListUserGroupsResponse], + ]: + r"""Return a callable for the list user groups method over gRPC. + + Returns a list of user groups in the specified GMP + organization. + + Returns: + Callable[[~.ListUserGroupsRequest], + Awaitable[~.ListUserGroupsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_user_groups" not in self._stubs: + self._stubs["list_user_groups"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/ListUserGroups", + request_serializer=marketingplatform_admin.ListUserGroupsRequest.serialize, + response_deserializer=marketingplatform_admin.ListUserGroupsResponse.deserialize, + ) + return self._stubs["list_user_groups"] + + @property + def create_user_group( + self, + ) -> Callable[ + [marketingplatform_admin.CreateUserGroupRequest], Awaitable[resources.UserGroup] + ]: + r"""Return a callable for the create user group method over gRPC. + + Creates a user group in the specified GMP + organization. + + Returns: + Callable[[~.CreateUserGroupRequest], + Awaitable[~.UserGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_user_group" not in self._stubs: + self._stubs["create_user_group"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/CreateUserGroup", + request_serializer=marketingplatform_admin.CreateUserGroupRequest.serialize, + response_deserializer=resources.UserGroup.deserialize, + ) + return self._stubs["create_user_group"] + + @property + def update_user_group( + self, + ) -> Callable[ + [marketingplatform_admin.UpdateUserGroupRequest], Awaitable[resources.UserGroup] + ]: + r"""Return a callable for the update user group method over gRPC. + + Updates a user group in the specified GMP + organization. + + Returns: + Callable[[~.UpdateUserGroupRequest], + Awaitable[~.UserGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_user_group" not in self._stubs: + self._stubs["update_user_group"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/UpdateUserGroup", + request_serializer=marketingplatform_admin.UpdateUserGroupRequest.serialize, + response_deserializer=resources.UserGroup.deserialize, + ) + return self._stubs["update_user_group"] + + @property + def delete_user_group( + self, + ) -> Callable[ + [marketingplatform_admin.DeleteUserGroupRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete user group method over gRPC. + + Deletes a user group in the specified GMP + organization. + + Returns: + Callable[[~.DeleteUserGroupRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_user_group" not in self._stubs: + self._stubs["delete_user_group"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/DeleteUserGroup", + request_serializer=marketingplatform_admin.DeleteUserGroupRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_user_group"] + + @property + def get_user_group_member( + self, + ) -> Callable[ + [marketingplatform_admin.GetUserGroupMemberRequest], + Awaitable[resources.UserGroupMember], + ]: + r"""Return a callable for the get user group member method over gRPC. + + Looks up a single user group member. + + Returns: + Callable[[~.GetUserGroupMemberRequest], + Awaitable[~.UserGroupMember]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_user_group_member" not in self._stubs: + self._stubs["get_user_group_member"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/GetUserGroupMember", + request_serializer=marketingplatform_admin.GetUserGroupMemberRequest.serialize, + response_deserializer=resources.UserGroupMember.deserialize, + ) + return self._stubs["get_user_group_member"] + + @property + def list_user_group_members( + self, + ) -> Callable[ + [marketingplatform_admin.ListUserGroupMembersRequest], + Awaitable[marketingplatform_admin.ListUserGroupMembersResponse], + ]: + r"""Return a callable for the list user group members method over gRPC. + + Returns a list of members in the specified user + group. + + Returns: + Callable[[~.ListUserGroupMembersRequest], + Awaitable[~.ListUserGroupMembersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_user_group_members" not in self._stubs: + self._stubs["list_user_group_members"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/ListUserGroupMembers", + request_serializer=marketingplatform_admin.ListUserGroupMembersRequest.serialize, + response_deserializer=marketingplatform_admin.ListUserGroupMembersResponse.deserialize, + ) + return self._stubs["list_user_group_members"] + + @property + def create_user_group_member( + self, + ) -> Callable[ + [marketingplatform_admin.CreateUserGroupMemberRequest], + Awaitable[resources.UserGroupMember], + ]: + r"""Return a callable for the create user group member method over gRPC. + + Adds a member to the specified GMP user group. + + Returns: + Callable[[~.CreateUserGroupMemberRequest], + Awaitable[~.UserGroupMember]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_user_group_member" not in self._stubs: + self._stubs["create_user_group_member"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/CreateUserGroupMember", + request_serializer=marketingplatform_admin.CreateUserGroupMemberRequest.serialize, + response_deserializer=resources.UserGroupMember.deserialize, + ) + return self._stubs["create_user_group_member"] + + @property + def update_user_group_member( + self, + ) -> Callable[ + [marketingplatform_admin.UpdateUserGroupMemberRequest], + Awaitable[resources.UserGroupMember], + ]: + r"""Return a callable for the update user group member method over gRPC. + + Updates a member in the specified GMP user group. + + Returns: + Callable[[~.UpdateUserGroupMemberRequest], + Awaitable[~.UserGroupMember]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_user_group_member" not in self._stubs: + self._stubs["update_user_group_member"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/UpdateUserGroupMember", + request_serializer=marketingplatform_admin.UpdateUserGroupMemberRequest.serialize, + response_deserializer=resources.UserGroupMember.deserialize, + ) + return self._stubs["update_user_group_member"] + + @property + def delete_user_group_member( + self, + ) -> Callable[ + [marketingplatform_admin.DeleteUserGroupMemberRequest], + Awaitable[empty_pb2.Empty], + ]: + r"""Return a callable for the delete user group member method over gRPC. + + Deletes a member in the specified GMP user group. + + Returns: + Callable[[~.DeleteUserGroupMemberRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_user_group_member" not in self._stubs: + self._stubs["delete_user_group_member"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/DeleteUserGroupMember", + request_serializer=marketingplatform_admin.DeleteUserGroupMemberRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_user_group_member"] + + @property + def get_admin_access_binding( + self, + ) -> Callable[ + [marketingplatform_admin.GetAdminAccessBindingRequest], + Awaitable[resources.AdminAccessBinding], + ]: + r"""Return a callable for the get admin access binding method over gRPC. + + Looks up a single admin access binding. + + Returns: + Callable[[~.GetAdminAccessBindingRequest], + Awaitable[~.AdminAccessBinding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_admin_access_binding" not in self._stubs: + self._stubs["get_admin_access_binding"] = self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/GetAdminAccessBinding", + request_serializer=marketingplatform_admin.GetAdminAccessBindingRequest.serialize, + response_deserializer=resources.AdminAccessBinding.deserialize, + ) + return self._stubs["get_admin_access_binding"] + + @property + def list_admin_access_bindings( + self, + ) -> Callable[ + [marketingplatform_admin.ListAdminAccessBindingsRequest], + Awaitable[marketingplatform_admin.ListAdminAccessBindingsResponse], + ]: + r"""Return a callable for the list admin access bindings method over gRPC. + + Returns a list of admin access bindings in the + specified GMP organization. + + Returns: + Callable[[~.ListAdminAccessBindingsRequest], + Awaitable[~.ListAdminAccessBindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_admin_access_bindings" not in self._stubs: + self._stubs["list_admin_access_bindings"] = ( + self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/ListAdminAccessBindings", + request_serializer=marketingplatform_admin.ListAdminAccessBindingsRequest.serialize, + response_deserializer=marketingplatform_admin.ListAdminAccessBindingsResponse.deserialize, + ) + ) + return self._stubs["list_admin_access_bindings"] + + @property + def create_admin_access_binding( + self, + ) -> Callable[ + [marketingplatform_admin.CreateAdminAccessBindingRequest], + Awaitable[resources.AdminAccessBinding], + ]: + r"""Return a callable for the create admin access binding method over gRPC. + + Creates an admin access binding in the specified GMP + organization. + + Returns: + Callable[[~.CreateAdminAccessBindingRequest], + Awaitable[~.AdminAccessBinding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_admin_access_binding" not in self._stubs: + self._stubs["create_admin_access_binding"] = ( + self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/CreateAdminAccessBinding", + request_serializer=marketingplatform_admin.CreateAdminAccessBindingRequest.serialize, + response_deserializer=resources.AdminAccessBinding.deserialize, + ) + ) + return self._stubs["create_admin_access_binding"] + + @property + def update_admin_access_binding( + self, + ) -> Callable[ + [marketingplatform_admin.UpdateAdminAccessBindingRequest], + Awaitable[resources.AdminAccessBinding], + ]: + r"""Return a callable for the update admin access binding method over gRPC. + + Updates an admin access binding in the specified GMP + organization. + + Returns: + Callable[[~.UpdateAdminAccessBindingRequest], + Awaitable[~.AdminAccessBinding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_admin_access_binding" not in self._stubs: + self._stubs["update_admin_access_binding"] = ( + self._logged_channel.unary_unary( + "/google.marketingplatform.admin.v1alpha.MarketingplatformAdminService/UpdateAdminAccessBinding", + request_serializer=marketingplatform_admin.UpdateAdminAccessBindingRequest.serialize, + response_deserializer=resources.AdminAccessBinding.deserialize, + ) + ) + return self._stubs["update_admin_access_binding"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -654,6 +1070,76 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_user_group: self._wrap_method( + self.get_user_group, + default_timeout=None, + client_info=client_info, + ), + self.list_user_groups: self._wrap_method( + self.list_user_groups, + default_timeout=None, + client_info=client_info, + ), + self.create_user_group: self._wrap_method( + self.create_user_group, + default_timeout=None, + client_info=client_info, + ), + self.update_user_group: self._wrap_method( + self.update_user_group, + default_timeout=None, + client_info=client_info, + ), + self.delete_user_group: self._wrap_method( + self.delete_user_group, + default_timeout=None, + client_info=client_info, + ), + self.get_user_group_member: self._wrap_method( + self.get_user_group_member, + default_timeout=None, + client_info=client_info, + ), + self.list_user_group_members: self._wrap_method( + self.list_user_group_members, + default_timeout=None, + client_info=client_info, + ), + self.create_user_group_member: self._wrap_method( + self.create_user_group_member, + default_timeout=None, + client_info=client_info, + ), + self.update_user_group_member: self._wrap_method( + self.update_user_group_member, + default_timeout=None, + client_info=client_info, + ), + self.delete_user_group_member: self._wrap_method( + self.delete_user_group_member, + default_timeout=None, + client_info=client_info, + ), + self.get_admin_access_binding: self._wrap_method( + self.get_admin_access_binding, + default_timeout=None, + client_info=client_info, + ), + self.list_admin_access_bindings: self._wrap_method( + self.list_admin_access_bindings, + default_timeout=None, + client_info=client_info, + ), + self.create_admin_access_binding: self._wrap_method( + self.create_admin_access_binding, + default_timeout=None, + client_info=client_info, + ), + self.update_admin_access_binding: self._wrap_method( + self.update_admin_access_binding, + default_timeout=None, + client_info=client_info, + ), } def _wrap_method(self, func, *args, **kwargs): diff --git a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/rest.py b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/rest.py index 186bea649cf1..87dfa972e039 100644 --- a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/rest.py +++ b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/rest.py @@ -76,6 +76,14 @@ class MarketingplatformAdminServiceRestInterceptor: .. code-block:: python class MyCustomMarketingplatformAdminServiceInterceptor(MarketingplatformAdminServiceRestInterceptor): + def pre_create_admin_access_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_admin_access_binding(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_analytics_account_link(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -84,10 +92,34 @@ def post_create_analytics_account_link(self, response): logging.log(f"Received response: {response}") return response + def pre_create_user_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_user_group(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_user_group_member(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_user_group_member(self, response): + logging.log(f"Received response: {response}") + return response + def pre_delete_analytics_account_link(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata + def pre_delete_user_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_user_group_member(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + def pre_find_sales_partner_managed_clients(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -96,6 +128,14 @@ def post_find_sales_partner_managed_clients(self, response): logging.log(f"Received response: {response}") return response + def pre_get_admin_access_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_admin_access_binding(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_organization(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -104,6 +144,30 @@ def post_get_organization(self, response): logging.log(f"Received response: {response}") return response + def pre_get_user_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_user_group(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_user_group_member(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_user_group_member(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_admin_access_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_admin_access_bindings(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_analytics_account_links(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -120,6 +184,22 @@ def post_list_organizations(self, response): logging.log(f"Received response: {response}") return response + def pre_list_user_group_members(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_user_group_members(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_user_groups(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_user_groups(self, response): + logging.log(f"Received response: {response}") + return response + def pre_report_property_usage(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -136,12 +216,85 @@ def post_set_property_service_level(self, response): logging.log(f"Received response: {response}") return response + def pre_update_admin_access_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_admin_access_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_user_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_user_group(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_user_group_member(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_user_group_member(self, response): + logging.log(f"Received response: {response}") + return response + transport = MarketingplatformAdminServiceRestTransport(interceptor=MyCustomMarketingplatformAdminServiceInterceptor()) client = MarketingplatformAdminServiceClient(transport=transport) """ + def pre_create_admin_access_binding( + self, + request: marketingplatform_admin.CreateAdminAccessBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + marketingplatform_admin.CreateAdminAccessBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_admin_access_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the MarketingplatformAdminService server. + """ + return request, metadata + + def post_create_admin_access_binding( + self, response: resources.AdminAccessBinding + ) -> resources.AdminAccessBinding: + """Post-rpc interceptor for create_admin_access_binding + + DEPRECATED. Please use the `post_create_admin_access_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MarketingplatformAdminService server but before + it is returned to user code. This `post_create_admin_access_binding` interceptor runs + before the `post_create_admin_access_binding_with_metadata` interceptor. + """ + return response + + def post_create_admin_access_binding_with_metadata( + self, + response: resources.AdminAccessBinding, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resources.AdminAccessBinding, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_admin_access_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MarketingplatformAdminService server but before it is returned to user code. + + We recommend only using this `post_create_admin_access_binding_with_metadata` + interceptor in new development instead of the `post_create_admin_access_binding` interceptor. + When both interceptors are used, this `post_create_admin_access_binding_with_metadata` interceptor runs after the + `post_create_admin_access_binding` interceptor. The (possibly modified) response returned by + `post_create_admin_access_binding` will be passed to + `post_create_admin_access_binding_with_metadata`. + """ + return response, metadata + def pre_create_analytics_account_link( self, request: marketingplatform_admin.CreateAnalyticsAccountLinkRequest, @@ -191,6 +344,104 @@ def post_create_analytics_account_link_with_metadata( """ return response, metadata + def pre_create_user_group( + self, + request: marketingplatform_admin.CreateUserGroupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + marketingplatform_admin.CreateUserGroupRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_user_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the MarketingplatformAdminService server. + """ + return request, metadata + + def post_create_user_group( + self, response: resources.UserGroup + ) -> resources.UserGroup: + """Post-rpc interceptor for create_user_group + + DEPRECATED. Please use the `post_create_user_group_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MarketingplatformAdminService server but before + it is returned to user code. This `post_create_user_group` interceptor runs + before the `post_create_user_group_with_metadata` interceptor. + """ + return response + + def post_create_user_group_with_metadata( + self, + response: resources.UserGroup, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resources.UserGroup, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_user_group + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MarketingplatformAdminService server but before it is returned to user code. + + We recommend only using this `post_create_user_group_with_metadata` + interceptor in new development instead of the `post_create_user_group` interceptor. + When both interceptors are used, this `post_create_user_group_with_metadata` interceptor runs after the + `post_create_user_group` interceptor. The (possibly modified) response returned by + `post_create_user_group` will be passed to + `post_create_user_group_with_metadata`. + """ + return response, metadata + + def pre_create_user_group_member( + self, + request: marketingplatform_admin.CreateUserGroupMemberRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + marketingplatform_admin.CreateUserGroupMemberRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_user_group_member + + Override in a subclass to manipulate the request or metadata + before they are sent to the MarketingplatformAdminService server. + """ + return request, metadata + + def post_create_user_group_member( + self, response: resources.UserGroupMember + ) -> resources.UserGroupMember: + """Post-rpc interceptor for create_user_group_member + + DEPRECATED. Please use the `post_create_user_group_member_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MarketingplatformAdminService server but before + it is returned to user code. This `post_create_user_group_member` interceptor runs + before the `post_create_user_group_member_with_metadata` interceptor. + """ + return response + + def post_create_user_group_member_with_metadata( + self, + response: resources.UserGroupMember, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resources.UserGroupMember, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_user_group_member + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MarketingplatformAdminService server but before it is returned to user code. + + We recommend only using this `post_create_user_group_member_with_metadata` + interceptor in new development instead of the `post_create_user_group_member` interceptor. + When both interceptors are used, this `post_create_user_group_member_with_metadata` interceptor runs after the + `post_create_user_group_member` interceptor. The (possibly modified) response returned by + `post_create_user_group_member` will be passed to + `post_create_user_group_member_with_metadata`. + """ + return response, metadata + def pre_delete_analytics_account_link( self, request: marketingplatform_admin.DeleteAnalyticsAccountLinkRequest, @@ -206,6 +457,36 @@ def pre_delete_analytics_account_link( """ return request, metadata + def pre_delete_user_group( + self, + request: marketingplatform_admin.DeleteUserGroupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + marketingplatform_admin.DeleteUserGroupRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_user_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the MarketingplatformAdminService server. + """ + return request, metadata + + def pre_delete_user_group_member( + self, + request: marketingplatform_admin.DeleteUserGroupMemberRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + marketingplatform_admin.DeleteUserGroupMemberRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_user_group_member + + Override in a subclass to manipulate the request or metadata + before they are sent to the MarketingplatformAdminService server. + """ + return request, metadata + def pre_find_sales_partner_managed_clients( self, request: marketingplatform_admin.FindSalesPartnerManagedClientsRequest, @@ -258,6 +539,55 @@ def post_find_sales_partner_managed_clients_with_metadata( """ return response, metadata + def pre_get_admin_access_binding( + self, + request: marketingplatform_admin.GetAdminAccessBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + marketingplatform_admin.GetAdminAccessBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_admin_access_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the MarketingplatformAdminService server. + """ + return request, metadata + + def post_get_admin_access_binding( + self, response: resources.AdminAccessBinding + ) -> resources.AdminAccessBinding: + """Post-rpc interceptor for get_admin_access_binding + + DEPRECATED. Please use the `post_get_admin_access_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MarketingplatformAdminService server but before + it is returned to user code. This `post_get_admin_access_binding` interceptor runs + before the `post_get_admin_access_binding_with_metadata` interceptor. + """ + return response + + def post_get_admin_access_binding_with_metadata( + self, + response: resources.AdminAccessBinding, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resources.AdminAccessBinding, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_admin_access_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MarketingplatformAdminService server but before it is returned to user code. + + We recommend only using this `post_get_admin_access_binding_with_metadata` + interceptor in new development instead of the `post_get_admin_access_binding` interceptor. + When both interceptors are used, this `post_get_admin_access_binding_with_metadata` interceptor runs after the + `post_get_admin_access_binding` interceptor. The (possibly modified) response returned by + `post_get_admin_access_binding` will be passed to + `post_get_admin_access_binding_with_metadata`. + """ + return response, metadata + def pre_get_organization( self, request: marketingplatform_admin.GetOrganizationRequest, @@ -307,103 +637,251 @@ def post_get_organization_with_metadata( """ return response, metadata - def pre_list_analytics_account_links( + def pre_get_user_group( self, - request: marketingplatform_admin.ListAnalyticsAccountLinksRequest, + request: marketingplatform_admin.GetUserGroupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - marketingplatform_admin.ListAnalyticsAccountLinksRequest, + marketingplatform_admin.GetUserGroupRequest, Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for list_analytics_account_links + """Pre-rpc interceptor for get_user_group Override in a subclass to manipulate the request or metadata before they are sent to the MarketingplatformAdminService server. """ return request, metadata - def post_list_analytics_account_links( - self, response: marketingplatform_admin.ListAnalyticsAccountLinksResponse - ) -> marketingplatform_admin.ListAnalyticsAccountLinksResponse: - """Post-rpc interceptor for list_analytics_account_links + def post_get_user_group(self, response: resources.UserGroup) -> resources.UserGroup: + """Post-rpc interceptor for get_user_group - DEPRECATED. Please use the `post_list_analytics_account_links_with_metadata` + DEPRECATED. Please use the `post_get_user_group_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the MarketingplatformAdminService server but before - it is returned to user code. This `post_list_analytics_account_links` interceptor runs - before the `post_list_analytics_account_links_with_metadata` interceptor. + it is returned to user code. This `post_get_user_group` interceptor runs + before the `post_get_user_group_with_metadata` interceptor. """ return response - def post_list_analytics_account_links_with_metadata( + def post_get_user_group_with_metadata( self, - response: marketingplatform_admin.ListAnalyticsAccountLinksResponse, + response: resources.UserGroup, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - marketingplatform_admin.ListAnalyticsAccountLinksResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: - """Post-rpc interceptor for list_analytics_account_links + ) -> Tuple[resources.UserGroup, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_user_group Override in a subclass to read or manipulate the response or metadata after it is returned by the MarketingplatformAdminService server but before it is returned to user code. - We recommend only using this `post_list_analytics_account_links_with_metadata` - interceptor in new development instead of the `post_list_analytics_account_links` interceptor. - When both interceptors are used, this `post_list_analytics_account_links_with_metadata` interceptor runs after the - `post_list_analytics_account_links` interceptor. The (possibly modified) response returned by - `post_list_analytics_account_links` will be passed to - `post_list_analytics_account_links_with_metadata`. + We recommend only using this `post_get_user_group_with_metadata` + interceptor in new development instead of the `post_get_user_group` interceptor. + When both interceptors are used, this `post_get_user_group_with_metadata` interceptor runs after the + `post_get_user_group` interceptor. The (possibly modified) response returned by + `post_get_user_group` will be passed to + `post_get_user_group_with_metadata`. """ return response, metadata - def pre_list_organizations( + def pre_get_user_group_member( self, - request: marketingplatform_admin.ListOrganizationsRequest, + request: marketingplatform_admin.GetUserGroupMemberRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - marketingplatform_admin.ListOrganizationsRequest, + marketingplatform_admin.GetUserGroupMemberRequest, Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for list_organizations + """Pre-rpc interceptor for get_user_group_member Override in a subclass to manipulate the request or metadata before they are sent to the MarketingplatformAdminService server. """ return request, metadata - def post_list_organizations( - self, response: marketingplatform_admin.ListOrganizationsResponse - ) -> marketingplatform_admin.ListOrganizationsResponse: - """Post-rpc interceptor for list_organizations + def post_get_user_group_member( + self, response: resources.UserGroupMember + ) -> resources.UserGroupMember: + """Post-rpc interceptor for get_user_group_member - DEPRECATED. Please use the `post_list_organizations_with_metadata` + DEPRECATED. Please use the `post_get_user_group_member_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the MarketingplatformAdminService server but before - it is returned to user code. This `post_list_organizations` interceptor runs - before the `post_list_organizations_with_metadata` interceptor. + it is returned to user code. This `post_get_user_group_member` interceptor runs + before the `post_get_user_group_member_with_metadata` interceptor. """ return response - def post_list_organizations_with_metadata( + def post_get_user_group_member_with_metadata( self, - response: marketingplatform_admin.ListOrganizationsResponse, + response: resources.UserGroupMember, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - marketingplatform_admin.ListOrganizationsResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: - """Post-rpc interceptor for list_organizations + ) -> Tuple[resources.UserGroupMember, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_user_group_member Override in a subclass to read or manipulate the response or metadata after it is returned by the MarketingplatformAdminService server but before it is returned to user code. - We recommend only using this `post_list_organizations_with_metadata` - interceptor in new development instead of the `post_list_organizations` interceptor. + We recommend only using this `post_get_user_group_member_with_metadata` + interceptor in new development instead of the `post_get_user_group_member` interceptor. + When both interceptors are used, this `post_get_user_group_member_with_metadata` interceptor runs after the + `post_get_user_group_member` interceptor. The (possibly modified) response returned by + `post_get_user_group_member` will be passed to + `post_get_user_group_member_with_metadata`. + """ + return response, metadata + + def pre_list_admin_access_bindings( + self, + request: marketingplatform_admin.ListAdminAccessBindingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + marketingplatform_admin.ListAdminAccessBindingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_admin_access_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the MarketingplatformAdminService server. + """ + return request, metadata + + def post_list_admin_access_bindings( + self, response: marketingplatform_admin.ListAdminAccessBindingsResponse + ) -> marketingplatform_admin.ListAdminAccessBindingsResponse: + """Post-rpc interceptor for list_admin_access_bindings + + DEPRECATED. Please use the `post_list_admin_access_bindings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MarketingplatformAdminService server but before + it is returned to user code. This `post_list_admin_access_bindings` interceptor runs + before the `post_list_admin_access_bindings_with_metadata` interceptor. + """ + return response + + def post_list_admin_access_bindings_with_metadata( + self, + response: marketingplatform_admin.ListAdminAccessBindingsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + marketingplatform_admin.ListAdminAccessBindingsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_admin_access_bindings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MarketingplatformAdminService server but before it is returned to user code. + + We recommend only using this `post_list_admin_access_bindings_with_metadata` + interceptor in new development instead of the `post_list_admin_access_bindings` interceptor. + When both interceptors are used, this `post_list_admin_access_bindings_with_metadata` interceptor runs after the + `post_list_admin_access_bindings` interceptor. The (possibly modified) response returned by + `post_list_admin_access_bindings` will be passed to + `post_list_admin_access_bindings_with_metadata`. + """ + return response, metadata + + def pre_list_analytics_account_links( + self, + request: marketingplatform_admin.ListAnalyticsAccountLinksRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + marketingplatform_admin.ListAnalyticsAccountLinksRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_analytics_account_links + + Override in a subclass to manipulate the request or metadata + before they are sent to the MarketingplatformAdminService server. + """ + return request, metadata + + def post_list_analytics_account_links( + self, response: marketingplatform_admin.ListAnalyticsAccountLinksResponse + ) -> marketingplatform_admin.ListAnalyticsAccountLinksResponse: + """Post-rpc interceptor for list_analytics_account_links + + DEPRECATED. Please use the `post_list_analytics_account_links_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MarketingplatformAdminService server but before + it is returned to user code. This `post_list_analytics_account_links` interceptor runs + before the `post_list_analytics_account_links_with_metadata` interceptor. + """ + return response + + def post_list_analytics_account_links_with_metadata( + self, + response: marketingplatform_admin.ListAnalyticsAccountLinksResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + marketingplatform_admin.ListAnalyticsAccountLinksResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_analytics_account_links + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MarketingplatformAdminService server but before it is returned to user code. + + We recommend only using this `post_list_analytics_account_links_with_metadata` + interceptor in new development instead of the `post_list_analytics_account_links` interceptor. + When both interceptors are used, this `post_list_analytics_account_links_with_metadata` interceptor runs after the + `post_list_analytics_account_links` interceptor. The (possibly modified) response returned by + `post_list_analytics_account_links` will be passed to + `post_list_analytics_account_links_with_metadata`. + """ + return response, metadata + + def pre_list_organizations( + self, + request: marketingplatform_admin.ListOrganizationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + marketingplatform_admin.ListOrganizationsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_organizations + + Override in a subclass to manipulate the request or metadata + before they are sent to the MarketingplatformAdminService server. + """ + return request, metadata + + def post_list_organizations( + self, response: marketingplatform_admin.ListOrganizationsResponse + ) -> marketingplatform_admin.ListOrganizationsResponse: + """Post-rpc interceptor for list_organizations + + DEPRECATED. Please use the `post_list_organizations_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MarketingplatformAdminService server but before + it is returned to user code. This `post_list_organizations` interceptor runs + before the `post_list_organizations_with_metadata` interceptor. + """ + return response + + def post_list_organizations_with_metadata( + self, + response: marketingplatform_admin.ListOrganizationsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + marketingplatform_admin.ListOrganizationsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_organizations + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MarketingplatformAdminService server but before it is returned to user code. + + We recommend only using this `post_list_organizations_with_metadata` + interceptor in new development instead of the `post_list_organizations` interceptor. When both interceptors are used, this `post_list_organizations_with_metadata` interceptor runs after the `post_list_organizations` interceptor. The (possibly modified) response returned by `post_list_organizations` will be passed to @@ -411,6 +889,110 @@ def post_list_organizations_with_metadata( """ return response, metadata + def pre_list_user_group_members( + self, + request: marketingplatform_admin.ListUserGroupMembersRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + marketingplatform_admin.ListUserGroupMembersRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_user_group_members + + Override in a subclass to manipulate the request or metadata + before they are sent to the MarketingplatformAdminService server. + """ + return request, metadata + + def post_list_user_group_members( + self, response: marketingplatform_admin.ListUserGroupMembersResponse + ) -> marketingplatform_admin.ListUserGroupMembersResponse: + """Post-rpc interceptor for list_user_group_members + + DEPRECATED. Please use the `post_list_user_group_members_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MarketingplatformAdminService server but before + it is returned to user code. This `post_list_user_group_members` interceptor runs + before the `post_list_user_group_members_with_metadata` interceptor. + """ + return response + + def post_list_user_group_members_with_metadata( + self, + response: marketingplatform_admin.ListUserGroupMembersResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + marketingplatform_admin.ListUserGroupMembersResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_user_group_members + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MarketingplatformAdminService server but before it is returned to user code. + + We recommend only using this `post_list_user_group_members_with_metadata` + interceptor in new development instead of the `post_list_user_group_members` interceptor. + When both interceptors are used, this `post_list_user_group_members_with_metadata` interceptor runs after the + `post_list_user_group_members` interceptor. The (possibly modified) response returned by + `post_list_user_group_members` will be passed to + `post_list_user_group_members_with_metadata`. + """ + return response, metadata + + def pre_list_user_groups( + self, + request: marketingplatform_admin.ListUserGroupsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + marketingplatform_admin.ListUserGroupsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_user_groups + + Override in a subclass to manipulate the request or metadata + before they are sent to the MarketingplatformAdminService server. + """ + return request, metadata + + def post_list_user_groups( + self, response: marketingplatform_admin.ListUserGroupsResponse + ) -> marketingplatform_admin.ListUserGroupsResponse: + """Post-rpc interceptor for list_user_groups + + DEPRECATED. Please use the `post_list_user_groups_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MarketingplatformAdminService server but before + it is returned to user code. This `post_list_user_groups` interceptor runs + before the `post_list_user_groups_with_metadata` interceptor. + """ + return response + + def post_list_user_groups_with_metadata( + self, + response: marketingplatform_admin.ListUserGroupsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + marketingplatform_admin.ListUserGroupsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_user_groups + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MarketingplatformAdminService server but before it is returned to user code. + + We recommend only using this `post_list_user_groups_with_metadata` + interceptor in new development instead of the `post_list_user_groups` interceptor. + When both interceptors are used, this `post_list_user_groups_with_metadata` interceptor runs after the + `post_list_user_groups` interceptor. The (possibly modified) response returned by + `post_list_user_groups` will be passed to + `post_list_user_groups_with_metadata`. + """ + return response, metadata + def pre_report_property_usage( self, request: marketingplatform_admin.ReportPropertyUsageRequest, @@ -515,53 +1097,200 @@ def post_set_property_service_level_with_metadata( """ return response, metadata + def pre_update_admin_access_binding( + self, + request: marketingplatform_admin.UpdateAdminAccessBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + marketingplatform_admin.UpdateAdminAccessBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_admin_access_binding -@dataclasses.dataclass -class MarketingplatformAdminServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: MarketingplatformAdminServiceRestInterceptor + Override in a subclass to manipulate the request or metadata + before they are sent to the MarketingplatformAdminService server. + """ + return request, metadata + def post_update_admin_access_binding( + self, response: resources.AdminAccessBinding + ) -> resources.AdminAccessBinding: + """Post-rpc interceptor for update_admin_access_binding -class MarketingplatformAdminServiceRestTransport( - _BaseMarketingplatformAdminServiceRestTransport -): - """REST backend synchronous transport for MarketingplatformAdminService. + DEPRECATED. Please use the `post_update_admin_access_binding_with_metadata` + interceptor instead. - Service Interface for the Google Marketing Platform Admin - API. + Override in a subclass to read or manipulate the response + after it is returned by the MarketingplatformAdminService server but before + it is returned to user code. This `post_update_admin_access_binding` interceptor runs + before the `post_update_admin_access_binding_with_metadata` interceptor. + """ + return response - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. + def post_update_admin_access_binding_with_metadata( + self, + response: resources.AdminAccessBinding, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resources.AdminAccessBinding, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_admin_access_binding - It sends JSON representations of protocol buffers over HTTP/1.1 - """ + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MarketingplatformAdminService server but before it is returned to user code. - def __init__( + We recommend only using this `post_update_admin_access_binding_with_metadata` + interceptor in new development instead of the `post_update_admin_access_binding` interceptor. + When both interceptors are used, this `post_update_admin_access_binding_with_metadata` interceptor runs after the + `post_update_admin_access_binding` interceptor. The (possibly modified) response returned by + `post_update_admin_access_binding` will be passed to + `post_update_admin_access_binding_with_metadata`. + """ + return response, metadata + + def pre_update_user_group( self, - *, - host: str = "marketingplatformadmin.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[MarketingplatformAdminServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. + request: marketingplatform_admin.UpdateUserGroupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + marketingplatform_admin.UpdateUserGroupRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_user_group - Args: - host (Optional[str]): - The hostname to connect to (default: 'marketingplatformadmin.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the + Override in a subclass to manipulate the request or metadata + before they are sent to the MarketingplatformAdminService server. + """ + return request, metadata + + def post_update_user_group( + self, response: resources.UserGroup + ) -> resources.UserGroup: + """Post-rpc interceptor for update_user_group + + DEPRECATED. Please use the `post_update_user_group_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MarketingplatformAdminService server but before + it is returned to user code. This `post_update_user_group` interceptor runs + before the `post_update_user_group_with_metadata` interceptor. + """ + return response + + def post_update_user_group_with_metadata( + self, + response: resources.UserGroup, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resources.UserGroup, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_user_group + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MarketingplatformAdminService server but before it is returned to user code. + + We recommend only using this `post_update_user_group_with_metadata` + interceptor in new development instead of the `post_update_user_group` interceptor. + When both interceptors are used, this `post_update_user_group_with_metadata` interceptor runs after the + `post_update_user_group` interceptor. The (possibly modified) response returned by + `post_update_user_group` will be passed to + `post_update_user_group_with_metadata`. + """ + return response, metadata + + def pre_update_user_group_member( + self, + request: marketingplatform_admin.UpdateUserGroupMemberRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + marketingplatform_admin.UpdateUserGroupMemberRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_user_group_member + + Override in a subclass to manipulate the request or metadata + before they are sent to the MarketingplatformAdminService server. + """ + return request, metadata + + def post_update_user_group_member( + self, response: resources.UserGroupMember + ) -> resources.UserGroupMember: + """Post-rpc interceptor for update_user_group_member + + DEPRECATED. Please use the `post_update_user_group_member_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MarketingplatformAdminService server but before + it is returned to user code. This `post_update_user_group_member` interceptor runs + before the `post_update_user_group_member_with_metadata` interceptor. + """ + return response + + def post_update_user_group_member_with_metadata( + self, + response: resources.UserGroupMember, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resources.UserGroupMember, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_user_group_member + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MarketingplatformAdminService server but before it is returned to user code. + + We recommend only using this `post_update_user_group_member_with_metadata` + interceptor in new development instead of the `post_update_user_group_member` interceptor. + When both interceptors are used, this `post_update_user_group_member_with_metadata` interceptor runs after the + `post_update_user_group_member` interceptor. The (possibly modified) response returned by + `post_update_user_group_member` will be passed to + `post_update_user_group_member_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class MarketingplatformAdminServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: MarketingplatformAdminServiceRestInterceptor + + +class MarketingplatformAdminServiceRestTransport( + _BaseMarketingplatformAdminServiceRestTransport +): + """REST backend synchronous transport for MarketingplatformAdminService. + + Service Interface for the Google Marketing Platform Admin + API. + + 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 = "marketingplatformadmin.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[MarketingplatformAdminServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'marketingplatformadmin.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the credentials from the environment. credentials_file (Optional[str]): Deprecated. A file with credentials that can @@ -614,6 +1343,160 @@ def __init__( ) self._prep_wrapped_messages(client_info) + class _CreateAdminAccessBinding( + _BaseMarketingplatformAdminServiceRestTransport._BaseCreateAdminAccessBinding, + MarketingplatformAdminServiceRestStub, + ): + def __hash__(self): + return hash( + "MarketingplatformAdminServiceRestTransport.CreateAdminAccessBinding" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: marketingplatform_admin.CreateAdminAccessBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.AdminAccessBinding: + r"""Call the create admin access + binding method over HTTP. + + Args: + request (~.marketingplatform_admin.CreateAdminAccessBindingRequest): + The request object. Request message for + CreateAdminAccessBinding RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.resources.AdminAccessBinding: + A resource message representing a + binding to a set of roles. + + """ + + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseCreateAdminAccessBinding._get_http_options() + request, metadata = self._interceptor.pre_create_admin_access_binding( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMarketingplatformAdminServiceRestTransport._BaseCreateAdminAccessBinding, + "_BaseCreateAdminAccessBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.CreateAdminAccessBinding", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "CreateAdminAccessBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MarketingplatformAdminServiceRestTransport._CreateAdminAccessBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.AdminAccessBinding() + pb_resp = resources.AdminAccessBinding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_admin_access_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_admin_access_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resources.AdminAccessBinding.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.create_admin_access_binding", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "CreateAdminAccessBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _CreateAnalyticsAccountLink( _BaseMarketingplatformAdminServiceRestTransport._BaseCreateAnalyticsAccountLink, MarketingplatformAdminServiceRestStub, @@ -721,14 +1604,1870 @@ def __call__( ) # Send the request - response = MarketingplatformAdminServiceRestTransport._CreateAnalyticsAccountLink._get_response( + response = MarketingplatformAdminServiceRestTransport._CreateAnalyticsAccountLink._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.AnalyticsAccountLink() + pb_resp = resources.AnalyticsAccountLink.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_analytics_account_link(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_analytics_account_link_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resources.AnalyticsAccountLink.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.create_analytics_account_link", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "CreateAnalyticsAccountLink", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateUserGroup( + _BaseMarketingplatformAdminServiceRestTransport._BaseCreateUserGroup, + MarketingplatformAdminServiceRestStub, + ): + def __hash__(self): + return hash("MarketingplatformAdminServiceRestTransport.CreateUserGroup") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: marketingplatform_admin.CreateUserGroupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.UserGroup: + r"""Call the create user group method over HTTP. + + Args: + request (~.marketingplatform_admin.CreateUserGroupRequest): + The request object. Request message for CreateUserGroup + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.resources.UserGroup: + A resource message representing a + user group in a GMP organization. + + """ + + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseCreateUserGroup._get_http_options() + request, metadata = self._interceptor.pre_create_user_group( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMarketingplatformAdminServiceRestTransport._BaseCreateUserGroup, + "_BaseCreateUserGroup__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.CreateUserGroup", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "CreateUserGroup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MarketingplatformAdminServiceRestTransport._CreateUserGroup._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.UserGroup() + pb_resp = resources.UserGroup.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_user_group(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_user_group_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resources.UserGroup.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.create_user_group", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "CreateUserGroup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateUserGroupMember( + _BaseMarketingplatformAdminServiceRestTransport._BaseCreateUserGroupMember, + MarketingplatformAdminServiceRestStub, + ): + def __hash__(self): + return hash( + "MarketingplatformAdminServiceRestTransport.CreateUserGroupMember" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: marketingplatform_admin.CreateUserGroupMemberRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.UserGroupMember: + r"""Call the create user group member method over HTTP. + + Args: + request (~.marketingplatform_admin.CreateUserGroupMemberRequest): + The request object. Request message for + CreateUserGroupMember RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.resources.UserGroupMember: + A resource message representing a + member of a user group. + + """ + + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseCreateUserGroupMember._get_http_options() + request, metadata = self._interceptor.pre_create_user_group_member( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMarketingplatformAdminServiceRestTransport._BaseCreateUserGroupMember, + "_BaseCreateUserGroupMember__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.CreateUserGroupMember", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "CreateUserGroupMember", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MarketingplatformAdminServiceRestTransport._CreateUserGroupMember._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.UserGroupMember() + pb_resp = resources.UserGroupMember.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_user_group_member(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_user_group_member_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resources.UserGroupMember.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.create_user_group_member", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "CreateUserGroupMember", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAnalyticsAccountLink( + _BaseMarketingplatformAdminServiceRestTransport._BaseDeleteAnalyticsAccountLink, + MarketingplatformAdminServiceRestStub, + ): + def __hash__(self): + return hash( + "MarketingplatformAdminServiceRestTransport.DeleteAnalyticsAccountLink" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: marketingplatform_admin.DeleteAnalyticsAccountLinkRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete analytics account + link method over HTTP. + + Args: + request (~.marketingplatform_admin.DeleteAnalyticsAccountLinkRequest): + The request object. Request message for + DeleteAnalyticsAccountLink RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseDeleteAnalyticsAccountLink._get_http_options() + request, metadata = self._interceptor.pre_delete_analytics_account_link( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMarketingplatformAdminServiceRestTransport._BaseDeleteAnalyticsAccountLink, + "_BaseDeleteAnalyticsAccountLink__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.DeleteAnalyticsAccountLink", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "DeleteAnalyticsAccountLink", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MarketingplatformAdminServiceRestTransport._DeleteAnalyticsAccountLink._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteUserGroup( + _BaseMarketingplatformAdminServiceRestTransport._BaseDeleteUserGroup, + MarketingplatformAdminServiceRestStub, + ): + def __hash__(self): + return hash("MarketingplatformAdminServiceRestTransport.DeleteUserGroup") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: marketingplatform_admin.DeleteUserGroupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete user group method over HTTP. + + Args: + request (~.marketingplatform_admin.DeleteUserGroupRequest): + The request object. Request message for DeleteUserGroup + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseDeleteUserGroup._get_http_options() + request, metadata = self._interceptor.pre_delete_user_group( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMarketingplatformAdminServiceRestTransport._BaseDeleteUserGroup, + "_BaseDeleteUserGroup__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.DeleteUserGroup", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "DeleteUserGroup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MarketingplatformAdminServiceRestTransport._DeleteUserGroup._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteUserGroupMember( + _BaseMarketingplatformAdminServiceRestTransport._BaseDeleteUserGroupMember, + MarketingplatformAdminServiceRestStub, + ): + def __hash__(self): + return hash( + "MarketingplatformAdminServiceRestTransport.DeleteUserGroupMember" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: marketingplatform_admin.DeleteUserGroupMemberRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete user group member method over HTTP. + + Args: + request (~.marketingplatform_admin.DeleteUserGroupMemberRequest): + The request object. Request message for + DeleteUserGroupMember RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseDeleteUserGroupMember._get_http_options() + request, metadata = self._interceptor.pre_delete_user_group_member( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMarketingplatformAdminServiceRestTransport._BaseDeleteUserGroupMember, + "_BaseDeleteUserGroupMember__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.DeleteUserGroupMember", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "DeleteUserGroupMember", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MarketingplatformAdminServiceRestTransport._DeleteUserGroupMember._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _FindSalesPartnerManagedClients( + _BaseMarketingplatformAdminServiceRestTransport._BaseFindSalesPartnerManagedClients, + MarketingplatformAdminServiceRestStub, + ): + def __hash__(self): + return hash( + "MarketingplatformAdminServiceRestTransport.FindSalesPartnerManagedClients" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: marketingplatform_admin.FindSalesPartnerManagedClientsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> marketingplatform_admin.FindSalesPartnerManagedClientsResponse: + r"""Call the find sales partner + managed clients method over HTTP. + + Args: + request (~.marketingplatform_admin.FindSalesPartnerManagedClientsRequest): + The request object. Request message for + FindSalesPartnerManagedClients RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.marketingplatform_admin.FindSalesPartnerManagedClientsResponse: + Response message for + FindSalesPartnerManagedClients RPC. + + """ + + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseFindSalesPartnerManagedClients._get_http_options() + request, metadata = ( + self._interceptor.pre_find_sales_partner_managed_clients( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMarketingplatformAdminServiceRestTransport._BaseFindSalesPartnerManagedClients, + "_BaseFindSalesPartnerManagedClients__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.FindSalesPartnerManagedClients", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "FindSalesPartnerManagedClients", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MarketingplatformAdminServiceRestTransport._FindSalesPartnerManagedClients._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = marketingplatform_admin.FindSalesPartnerManagedClientsResponse() + pb_resp = marketingplatform_admin.FindSalesPartnerManagedClientsResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_find_sales_partner_managed_clients(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_find_sales_partner_managed_clients_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = marketingplatform_admin.FindSalesPartnerManagedClientsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.find_sales_partner_managed_clients", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "FindSalesPartnerManagedClients", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAdminAccessBinding( + _BaseMarketingplatformAdminServiceRestTransport._BaseGetAdminAccessBinding, + MarketingplatformAdminServiceRestStub, + ): + def __hash__(self): + return hash( + "MarketingplatformAdminServiceRestTransport.GetAdminAccessBinding" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: marketingplatform_admin.GetAdminAccessBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.AdminAccessBinding: + r"""Call the get admin access binding method over HTTP. + + Args: + request (~.marketingplatform_admin.GetAdminAccessBindingRequest): + The request object. Response message for + GetAdminAccessBinding RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.resources.AdminAccessBinding: + A resource message representing a + binding to a set of roles. + + """ + + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseGetAdminAccessBinding._get_http_options() + request, metadata = self._interceptor.pre_get_admin_access_binding( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMarketingplatformAdminServiceRestTransport._BaseGetAdminAccessBinding, + "_BaseGetAdminAccessBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.GetAdminAccessBinding", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "GetAdminAccessBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MarketingplatformAdminServiceRestTransport._GetAdminAccessBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.AdminAccessBinding() + pb_resp = resources.AdminAccessBinding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_admin_access_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_admin_access_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resources.AdminAccessBinding.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.get_admin_access_binding", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "GetAdminAccessBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetOrganization( + _BaseMarketingplatformAdminServiceRestTransport._BaseGetOrganization, + MarketingplatformAdminServiceRestStub, + ): + def __hash__(self): + return hash("MarketingplatformAdminServiceRestTransport.GetOrganization") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: marketingplatform_admin.GetOrganizationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.Organization: + r"""Call the get organization method over HTTP. + + Args: + request (~.marketingplatform_admin.GetOrganizationRequest): + The request object. Request message for GetOrganization + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.resources.Organization: + A resource message representing a + Google Marketing Platform organization. + + """ + + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseGetOrganization._get_http_options() + request, metadata = self._interceptor.pre_get_organization( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMarketingplatformAdminServiceRestTransport._BaseGetOrganization, + "_BaseGetOrganization__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.GetOrganization", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "GetOrganization", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MarketingplatformAdminServiceRestTransport._GetOrganization._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.Organization() + pb_resp = resources.Organization.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_organization(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_organization_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resources.Organization.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.get_organization", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "GetOrganization", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetUserGroup( + _BaseMarketingplatformAdminServiceRestTransport._BaseGetUserGroup, + MarketingplatformAdminServiceRestStub, + ): + def __hash__(self): + return hash("MarketingplatformAdminServiceRestTransport.GetUserGroup") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: marketingplatform_admin.GetUserGroupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.UserGroup: + r"""Call the get user group method over HTTP. + + Args: + request (~.marketingplatform_admin.GetUserGroupRequest): + The request object. Request message for GetUserGroup RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.resources.UserGroup: + A resource message representing a + user group in a GMP organization. + + """ + + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseGetUserGroup._get_http_options() + request, metadata = self._interceptor.pre_get_user_group(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMarketingplatformAdminServiceRestTransport._BaseGetUserGroup, + "_BaseGetUserGroup__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.GetUserGroup", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "GetUserGroup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + MarketingplatformAdminServiceRestTransport._GetUserGroup._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.UserGroup() + pb_resp = resources.UserGroup.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_user_group(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_user_group_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resources.UserGroup.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.get_user_group", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "GetUserGroup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetUserGroupMember( + _BaseMarketingplatformAdminServiceRestTransport._BaseGetUserGroupMember, + MarketingplatformAdminServiceRestStub, + ): + def __hash__(self): + return hash("MarketingplatformAdminServiceRestTransport.GetUserGroupMember") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: marketingplatform_admin.GetUserGroupMemberRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.UserGroupMember: + r"""Call the get user group member method over HTTP. + + Args: + request (~.marketingplatform_admin.GetUserGroupMemberRequest): + The request object. Request message for + GetUserGroupMember RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.resources.UserGroupMember: + A resource message representing a + member of a user group. + + """ + + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseGetUserGroupMember._get_http_options() + request, metadata = self._interceptor.pre_get_user_group_member( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMarketingplatformAdminServiceRestTransport._BaseGetUserGroupMember, + "_BaseGetUserGroupMember__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.GetUserGroupMember", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "GetUserGroupMember", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MarketingplatformAdminServiceRestTransport._GetUserGroupMember._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.UserGroupMember() + pb_resp = resources.UserGroupMember.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_user_group_member(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_user_group_member_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resources.UserGroupMember.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.get_user_group_member", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "GetUserGroupMember", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAdminAccessBindings( + _BaseMarketingplatformAdminServiceRestTransport._BaseListAdminAccessBindings, + MarketingplatformAdminServiceRestStub, + ): + def __hash__(self): + return hash( + "MarketingplatformAdminServiceRestTransport.ListAdminAccessBindings" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: marketingplatform_admin.ListAdminAccessBindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> marketingplatform_admin.ListAdminAccessBindingsResponse: + r"""Call the list admin access + bindings method over HTTP. + + Args: + request (~.marketingplatform_admin.ListAdminAccessBindingsRequest): + The request object. Request message for + ListAdminAccessBindings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.marketingplatform_admin.ListAdminAccessBindingsResponse: + Response message for + ListAdminAccessBindings RPC. + + """ + + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseListAdminAccessBindings._get_http_options() + request, metadata = self._interceptor.pre_list_admin_access_bindings( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMarketingplatformAdminServiceRestTransport._BaseListAdminAccessBindings, + "_BaseListAdminAccessBindings__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.ListAdminAccessBindings", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "ListAdminAccessBindings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MarketingplatformAdminServiceRestTransport._ListAdminAccessBindings._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = marketingplatform_admin.ListAdminAccessBindingsResponse() + pb_resp = marketingplatform_admin.ListAdminAccessBindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_admin_access_bindings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_admin_access_bindings_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + marketingplatform_admin.ListAdminAccessBindingsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.list_admin_access_bindings", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "ListAdminAccessBindings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAnalyticsAccountLinks( + _BaseMarketingplatformAdminServiceRestTransport._BaseListAnalyticsAccountLinks, + MarketingplatformAdminServiceRestStub, + ): + def __hash__(self): + return hash( + "MarketingplatformAdminServiceRestTransport.ListAnalyticsAccountLinks" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: marketingplatform_admin.ListAnalyticsAccountLinksRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> marketingplatform_admin.ListAnalyticsAccountLinksResponse: + r"""Call the list analytics account + links method over HTTP. + + Args: + request (~.marketingplatform_admin.ListAnalyticsAccountLinksRequest): + The request object. Request message for + ListAnalyticsAccountLinks RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.marketingplatform_admin.ListAnalyticsAccountLinksResponse: + Response message for + ListAnalyticsAccountLinks RPC. + + """ + + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseListAnalyticsAccountLinks._get_http_options() + request, metadata = self._interceptor.pre_list_analytics_account_links( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMarketingplatformAdminServiceRestTransport._BaseListAnalyticsAccountLinks, + "_BaseListAnalyticsAccountLinks__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.ListAnalyticsAccountLinks", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "ListAnalyticsAccountLinks", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MarketingplatformAdminServiceRestTransport._ListAnalyticsAccountLinks._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = marketingplatform_admin.ListAnalyticsAccountLinksResponse() + pb_resp = marketingplatform_admin.ListAnalyticsAccountLinksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_analytics_account_links(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_analytics_account_links_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = marketingplatform_admin.ListAnalyticsAccountLinksResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.list_analytics_account_links", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "ListAnalyticsAccountLinks", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListOrganizations( + _BaseMarketingplatformAdminServiceRestTransport._BaseListOrganizations, + MarketingplatformAdminServiceRestStub, + ): + def __hash__(self): + return hash("MarketingplatformAdminServiceRestTransport.ListOrganizations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: marketingplatform_admin.ListOrganizationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> marketingplatform_admin.ListOrganizationsResponse: + r"""Call the list organizations method over HTTP. + + Args: + request (~.marketingplatform_admin.ListOrganizationsRequest): + The request object. Request message for ListOrganizations + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.marketingplatform_admin.ListOrganizationsResponse: + Response message for + ListOrganizations RPC. + + """ + + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseListOrganizations._get_http_options() + request, metadata = self._interceptor.pre_list_organizations( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseMarketingplatformAdminServiceRestTransport._BaseListOrganizations, + "_BaseListOrganizations__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.ListOrganizations", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "ListOrganizations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MarketingplatformAdminServiceRestTransport._ListOrganizations._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -737,23 +3476,25 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = resources.AnalyticsAccountLink() - pb_resp = resources.AnalyticsAccountLink.pb(resp) + resp = marketingplatform_admin.ListOrganizationsResponse() + pb_resp = marketingplatform_admin.ListOrganizationsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_analytics_account_link(resp) + resp = self._interceptor.post_list_organizations(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_create_analytics_account_link_with_metadata( - resp, response_metadata - ) + resp, _ = self._interceptor.post_list_organizations_with_metadata( + resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = resources.AnalyticsAccountLink.to_json(response) + response_payload = ( + marketingplatform_admin.ListOrganizationsResponse.to_json( + response + ) + ) except: response_payload = None http_response = { @@ -762,23 +3503,23 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.create_analytics_account_link", + "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.list_organizations", extra={ "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", - "rpcName": "CreateAnalyticsAccountLink", + "rpcName": "ListOrganizations", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteAnalyticsAccountLink( - _BaseMarketingplatformAdminServiceRestTransport._BaseDeleteAnalyticsAccountLink, + class _ListUserGroupMembers( + _BaseMarketingplatformAdminServiceRestTransport._BaseListUserGroupMembers, MarketingplatformAdminServiceRestStub, ): def __hash__(self): return hash( - "MarketingplatformAdminServiceRestTransport.DeleteAnalyticsAccountLink" + "MarketingplatformAdminServiceRestTransport.ListUserGroupMembers" ) @staticmethod @@ -805,38 +3546,43 @@ def _get_response( def __call__( self, - request: marketingplatform_admin.DeleteAnalyticsAccountLinkRequest, + request: marketingplatform_admin.ListUserGroupMembersRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ): - r"""Call the delete analytics account - link method over HTTP. + ) -> marketingplatform_admin.ListUserGroupMembersResponse: + r"""Call the list user group members method over HTTP. + + Args: + request (~.marketingplatform_admin.ListUserGroupMembersRequest): + The request object. Request message for + ListUserGroupMembers RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.marketingplatform_admin.ListUserGroupMembersResponse: + Response message for + ListUserGroupMembers RPC. - Args: - request (~.marketingplatform_admin.DeleteAnalyticsAccountLinkRequest): - The request object. Request message for - DeleteAnalyticsAccountLink RPC. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. """ - http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseDeleteAnalyticsAccountLink._get_http_options() - request, metadata = self._interceptor.pre_delete_analytics_account_link( + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseListUserGroupMembers._get_http_options() + request, metadata = self._interceptor.pre_list_user_group_members( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseMarketingplatformAdminServiceRestTransport._BaseDeleteAnalyticsAccountLink, - "_BaseDeleteAnalyticsAccountLink__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseMarketingplatformAdminServiceRestTransport._BaseListUserGroupMembers, + "_BaseListUserGroupMembers__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -860,17 +3606,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.DeleteAnalyticsAccountLink", + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.ListUserGroupMembers", extra={ "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", - "rpcName": "DeleteAnalyticsAccountLink", + "rpcName": "ListUserGroupMembers", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = MarketingplatformAdminServiceRestTransport._DeleteAnalyticsAccountLink._get_response( + response = MarketingplatformAdminServiceRestTransport._ListUserGroupMembers._get_response( self._host, metadata, query_params, @@ -884,14 +3630,50 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _FindSalesPartnerManagedClients( - _BaseMarketingplatformAdminServiceRestTransport._BaseFindSalesPartnerManagedClients, + # Return the response + resp = marketingplatform_admin.ListUserGroupMembersResponse() + pb_resp = marketingplatform_admin.ListUserGroupMembersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_user_group_members(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_user_group_members_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + marketingplatform_admin.ListUserGroupMembersResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.list_user_group_members", + extra={ + "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "rpcName": "ListUserGroupMembers", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListUserGroups( + _BaseMarketingplatformAdminServiceRestTransport._BaseListUserGroups, MarketingplatformAdminServiceRestStub, ): def __hash__(self): - return hash( - "MarketingplatformAdminServiceRestTransport.FindSalesPartnerManagedClients" - ) + return hash("MarketingplatformAdminServiceRestTransport.ListUserGroups") @staticmethod def _get_response( @@ -912,52 +3694,48 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, ) return response def __call__( self, - request: marketingplatform_admin.FindSalesPartnerManagedClientsRequest, + request: marketingplatform_admin.ListUserGroupsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> marketingplatform_admin.FindSalesPartnerManagedClientsResponse: - r"""Call the find sales partner - managed clients method over HTTP. + ) -> marketingplatform_admin.ListUserGroupsResponse: + r"""Call the list user groups method over HTTP. - Args: - request (~.marketingplatform_admin.FindSalesPartnerManagedClientsRequest): - The request object. Request message for - FindSalesPartnerManagedClients RPC. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. + Args: + request (~.marketingplatform_admin.ListUserGroupsRequest): + The request object. Request message for ListUserGroups + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. - Returns: - ~.marketingplatform_admin.FindSalesPartnerManagedClientsResponse: - Response message for - FindSalesPartnerManagedClients RPC. + Returns: + ~.marketingplatform_admin.ListUserGroupsResponse: + Response message for ListUserGroups + RPC. """ - http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseFindSalesPartnerManagedClients._get_http_options() - request, metadata = ( - self._interceptor.pre_find_sales_partner_managed_clients( - request, metadata - ) + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseListUserGroups._get_http_options() + request, metadata = self._interceptor.pre_list_user_groups( + request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseMarketingplatformAdminServiceRestTransport._BaseFindSalesPartnerManagedClients, - "_BaseFindSalesPartnerManagedClients__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseMarketingplatformAdminServiceRestTransport._BaseListUserGroups, + "_BaseListUserGroups__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -981,24 +3759,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.FindSalesPartnerManagedClients", + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.ListUserGroups", extra={ "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", - "rpcName": "FindSalesPartnerManagedClients", + "rpcName": "ListUserGroups", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = MarketingplatformAdminServiceRestTransport._FindSalesPartnerManagedClients._get_response( + response = MarketingplatformAdminServiceRestTransport._ListUserGroups._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1007,26 +3784,22 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = marketingplatform_admin.FindSalesPartnerManagedClientsResponse() - pb_resp = marketingplatform_admin.FindSalesPartnerManagedClientsResponse.pb( - resp - ) + resp = marketingplatform_admin.ListUserGroupsResponse() + pb_resp = marketingplatform_admin.ListUserGroupsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_find_sales_partner_managed_clients(resp) + resp = self._interceptor.post_list_user_groups(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_find_sales_partner_managed_clients_with_metadata( - resp, response_metadata - ) + resp, _ = self._interceptor.post_list_user_groups_with_metadata( + resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = marketingplatform_admin.FindSalesPartnerManagedClientsResponse.to_json( - response + response_payload = ( + marketingplatform_admin.ListUserGroupsResponse.to_json(response) ) except: response_payload = None @@ -1036,22 +3809,24 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.find_sales_partner_managed_clients", + "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.list_user_groups", extra={ "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", - "rpcName": "FindSalesPartnerManagedClients", + "rpcName": "ListUserGroups", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetOrganization( - _BaseMarketingplatformAdminServiceRestTransport._BaseGetOrganization, + class _ReportPropertyUsage( + _BaseMarketingplatformAdminServiceRestTransport._BaseReportPropertyUsage, MarketingplatformAdminServiceRestStub, ): def __hash__(self): - return hash("MarketingplatformAdminServiceRestTransport.GetOrganization") + return hash( + "MarketingplatformAdminServiceRestTransport.ReportPropertyUsage" + ) @staticmethod def _get_response( @@ -1072,23 +3847,24 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: marketingplatform_admin.GetOrganizationRequest, + request: marketingplatform_admin.ReportPropertyUsageRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> resources.Organization: - r"""Call the get organization method over HTTP. + ) -> marketingplatform_admin.ReportPropertyUsageResponse: + r"""Call the report property usage method over HTTP. Args: - request (~.marketingplatform_admin.GetOrganizationRequest): - The request object. Request message for GetOrganization - RPC. + request (~.marketingplatform_admin.ReportPropertyUsageRequest): + The request object. Request message for + ReportPropertyUsage RPC. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1098,22 +3874,22 @@ def __call__( be of type `bytes`. Returns: - ~.resources.Organization: - A resource message representing a - Google Marketing Platform organization. + ~.marketingplatform_admin.ReportPropertyUsageResponse: + Response message for + ReportPropertyUsage RPC. """ - http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseGetOrganization._get_http_options() - request, metadata = self._interceptor.pre_get_organization( + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseReportPropertyUsage._get_http_options() + request, metadata = self._interceptor.pre_report_property_usage( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseMarketingplatformAdminServiceRestTransport._BaseGetOrganization, - "_BaseGetOrganization__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseMarketingplatformAdminServiceRestTransport._BaseReportPropertyUsage, + "_BaseReportPropertyUsage__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -1137,23 +3913,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.GetOrganization", + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.ReportPropertyUsage", extra={ "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", - "rpcName": "GetOrganization", + "rpcName": "ReportPropertyUsage", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = MarketingplatformAdminServiceRestTransport._GetOrganization._get_response( + response = MarketingplatformAdminServiceRestTransport._ReportPropertyUsage._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1162,21 +3939,25 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = resources.Organization() - pb_resp = resources.Organization.pb(resp) + resp = marketingplatform_admin.ReportPropertyUsageResponse() + pb_resp = marketingplatform_admin.ReportPropertyUsageResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_organization(resp) + resp = self._interceptor.post_report_property_usage(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_organization_with_metadata( + resp, _ = self._interceptor.post_report_property_usage_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = resources.Organization.to_json(response) + response_payload = ( + marketingplatform_admin.ReportPropertyUsageResponse.to_json( + response + ) + ) except: response_payload = None http_response = { @@ -1185,23 +3966,23 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.get_organization", + "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.report_property_usage", extra={ "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", - "rpcName": "GetOrganization", + "rpcName": "ReportPropertyUsage", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListAnalyticsAccountLinks( - _BaseMarketingplatformAdminServiceRestTransport._BaseListAnalyticsAccountLinks, + class _SetPropertyServiceLevel( + _BaseMarketingplatformAdminServiceRestTransport._BaseSetPropertyServiceLevel, MarketingplatformAdminServiceRestStub, ): def __hash__(self): return hash( - "MarketingplatformAdminServiceRestTransport.ListAnalyticsAccountLinks" + "MarketingplatformAdminServiceRestTransport.SetPropertyServiceLevel" ) @staticmethod @@ -1223,24 +4004,25 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: marketingplatform_admin.ListAnalyticsAccountLinksRequest, + request: marketingplatform_admin.SetPropertyServiceLevelRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> marketingplatform_admin.ListAnalyticsAccountLinksResponse: - r"""Call the list analytics account - links method over HTTP. + ) -> marketingplatform_admin.SetPropertyServiceLevelResponse: + r"""Call the set property service + level method over HTTP. Args: - request (~.marketingplatform_admin.ListAnalyticsAccountLinksRequest): + request (~.marketingplatform_admin.SetPropertyServiceLevelRequest): The request object. Request message for - ListAnalyticsAccountLinks RPC. + SetPropertyServiceLevel RPC. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1250,22 +4032,22 @@ def __call__( be of type `bytes`. Returns: - ~.marketingplatform_admin.ListAnalyticsAccountLinksResponse: + ~.marketingplatform_admin.SetPropertyServiceLevelResponse: Response message for - ListAnalyticsAccountLinks RPC. + SetPropertyServiceLevel RPC. """ - http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseListAnalyticsAccountLinks._get_http_options() - request, metadata = self._interceptor.pre_list_analytics_account_links( + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseSetPropertyServiceLevel._get_http_options() + request, metadata = self._interceptor.pre_set_property_service_level( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseMarketingplatformAdminServiceRestTransport._BaseListAnalyticsAccountLinks, - "_BaseListAnalyticsAccountLinks__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseMarketingplatformAdminServiceRestTransport._BaseSetPropertyServiceLevel, + "_BaseSetPropertyServiceLevel__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -1289,23 +4071,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.ListAnalyticsAccountLinks", + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.SetPropertyServiceLevel", extra={ "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", - "rpcName": "ListAnalyticsAccountLinks", + "rpcName": "SetPropertyServiceLevel", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = MarketingplatformAdminServiceRestTransport._ListAnalyticsAccountLinks._get_response( + response = MarketingplatformAdminServiceRestTransport._SetPropertyServiceLevel._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1314,22 +4097,24 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = marketingplatform_admin.ListAnalyticsAccountLinksResponse() - pb_resp = marketingplatform_admin.ListAnalyticsAccountLinksResponse.pb(resp) + resp = marketingplatform_admin.SetPropertyServiceLevelResponse() + pb_resp = marketingplatform_admin.SetPropertyServiceLevelResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_analytics_account_links(resp) + resp = self._interceptor.post_set_property_service_level(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_analytics_account_links_with_metadata( + resp, _ = self._interceptor.post_set_property_service_level_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = marketingplatform_admin.ListAnalyticsAccountLinksResponse.to_json( - response + response_payload = ( + marketingplatform_admin.SetPropertyServiceLevelResponse.to_json( + response + ) ) except: response_payload = None @@ -1339,22 +4124,24 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.list_analytics_account_links", + "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.set_property_service_level", extra={ "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", - "rpcName": "ListAnalyticsAccountLinks", + "rpcName": "SetPropertyServiceLevel", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListOrganizations( - _BaseMarketingplatformAdminServiceRestTransport._BaseListOrganizations, + class _UpdateAdminAccessBinding( + _BaseMarketingplatformAdminServiceRestTransport._BaseUpdateAdminAccessBinding, MarketingplatformAdminServiceRestStub, ): def __hash__(self): - return hash("MarketingplatformAdminServiceRestTransport.ListOrganizations") + return hash( + "MarketingplatformAdminServiceRestTransport.UpdateAdminAccessBinding" + ) @staticmethod def _get_response( @@ -1375,48 +4162,50 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: marketingplatform_admin.ListOrganizationsRequest, + request: marketingplatform_admin.UpdateAdminAccessBindingRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> marketingplatform_admin.ListOrganizationsResponse: - r"""Call the list organizations method over HTTP. + ) -> resources.AdminAccessBinding: + r"""Call the update admin access + binding method over HTTP. - Args: - request (~.marketingplatform_admin.ListOrganizationsRequest): - The request object. Request message for ListOrganizations - RPC. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. + Args: + request (~.marketingplatform_admin.UpdateAdminAccessBindingRequest): + The request object. Request message for + UpdateAdminAccessBinding RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. - Returns: - ~.marketingplatform_admin.ListOrganizationsResponse: - Response message for - ListOrganizations RPC. + Returns: + ~.resources.AdminAccessBinding: + A resource message representing a + binding to a set of roles. """ - http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseListOrganizations._get_http_options() - request, metadata = self._interceptor.pre_list_organizations( + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseUpdateAdminAccessBinding._get_http_options() + request, metadata = self._interceptor.pre_update_admin_access_binding( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseMarketingplatformAdminServiceRestTransport._BaseListOrganizations, - "_BaseListOrganizations__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseMarketingplatformAdminServiceRestTransport._BaseUpdateAdminAccessBinding, + "_BaseUpdateAdminAccessBinding__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -1440,23 +4229,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.ListOrganizations", + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.UpdateAdminAccessBinding", extra={ "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", - "rpcName": "ListOrganizations", + "rpcName": "UpdateAdminAccessBinding", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = MarketingplatformAdminServiceRestTransport._ListOrganizations._get_response( + response = MarketingplatformAdminServiceRestTransport._UpdateAdminAccessBinding._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1465,25 +4255,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = marketingplatform_admin.ListOrganizationsResponse() - pb_resp = marketingplatform_admin.ListOrganizationsResponse.pb(resp) + resp = resources.AdminAccessBinding() + pb_resp = resources.AdminAccessBinding.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_organizations(resp) + resp = self._interceptor.post_update_admin_access_binding(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_organizations_with_metadata( + resp, _ = self._interceptor.post_update_admin_access_binding_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - marketingplatform_admin.ListOrganizationsResponse.to_json( - response - ) - ) + response_payload = resources.AdminAccessBinding.to_json(response) except: response_payload = None http_response = { @@ -1492,24 +4278,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.list_organizations", + "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.update_admin_access_binding", extra={ "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", - "rpcName": "ListOrganizations", + "rpcName": "UpdateAdminAccessBinding", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ReportPropertyUsage( - _BaseMarketingplatformAdminServiceRestTransport._BaseReportPropertyUsage, + class _UpdateUserGroup( + _BaseMarketingplatformAdminServiceRestTransport._BaseUpdateUserGroup, MarketingplatformAdminServiceRestStub, ): def __hash__(self): - return hash( - "MarketingplatformAdminServiceRestTransport.ReportPropertyUsage" - ) + return hash("MarketingplatformAdminServiceRestTransport.UpdateUserGroup") @staticmethod def _get_response( @@ -1536,18 +4320,18 @@ def _get_response( def __call__( self, - request: marketingplatform_admin.ReportPropertyUsageRequest, + request: marketingplatform_admin.UpdateUserGroupRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> marketingplatform_admin.ReportPropertyUsageResponse: - r"""Call the report property usage method over HTTP. + ) -> resources.UserGroup: + r"""Call the update user group method over HTTP. Args: - request (~.marketingplatform_admin.ReportPropertyUsageRequest): - The request object. Request message for - ReportPropertyUsage RPC. + request (~.marketingplatform_admin.UpdateUserGroupRequest): + The request object. Request message for UpdateUserGroup + RPC. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1557,22 +4341,22 @@ def __call__( be of type `bytes`. Returns: - ~.marketingplatform_admin.ReportPropertyUsageResponse: - Response message for - ReportPropertyUsage RPC. + ~.resources.UserGroup: + A resource message representing a + user group in a GMP organization. """ - http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseReportPropertyUsage._get_http_options() - request, metadata = self._interceptor.pre_report_property_usage( + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseUpdateUserGroup._get_http_options() + request, metadata = self._interceptor.pre_update_user_group( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseMarketingplatformAdminServiceRestTransport._BaseReportPropertyUsage, - "_BaseReportPropertyUsage__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseMarketingplatformAdminServiceRestTransport._BaseUpdateUserGroup, + "_BaseUpdateUserGroup__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -1596,17 +4380,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.ReportPropertyUsage", + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.UpdateUserGroup", extra={ "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", - "rpcName": "ReportPropertyUsage", + "rpcName": "UpdateUserGroup", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = MarketingplatformAdminServiceRestTransport._ReportPropertyUsage._get_response( + response = MarketingplatformAdminServiceRestTransport._UpdateUserGroup._get_response( self._host, metadata, query_params, @@ -1622,25 +4406,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = marketingplatform_admin.ReportPropertyUsageResponse() - pb_resp = marketingplatform_admin.ReportPropertyUsageResponse.pb(resp) + resp = resources.UserGroup() + pb_resp = resources.UserGroup.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_report_property_usage(resp) + resp = self._interceptor.post_update_user_group(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_report_property_usage_with_metadata( + resp, _ = self._interceptor.post_update_user_group_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - marketingplatform_admin.ReportPropertyUsageResponse.to_json( - response - ) - ) + response_payload = resources.UserGroup.to_json(response) except: response_payload = None http_response = { @@ -1649,23 +4429,23 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.report_property_usage", + "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.update_user_group", extra={ "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", - "rpcName": "ReportPropertyUsage", + "rpcName": "UpdateUserGroup", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _SetPropertyServiceLevel( - _BaseMarketingplatformAdminServiceRestTransport._BaseSetPropertyServiceLevel, + class _UpdateUserGroupMember( + _BaseMarketingplatformAdminServiceRestTransport._BaseUpdateUserGroupMember, MarketingplatformAdminServiceRestStub, ): def __hash__(self): return hash( - "MarketingplatformAdminServiceRestTransport.SetPropertyServiceLevel" + "MarketingplatformAdminServiceRestTransport.UpdateUserGroupMember" ) @staticmethod @@ -1693,44 +4473,43 @@ def _get_response( def __call__( self, - request: marketingplatform_admin.SetPropertyServiceLevelRequest, + request: marketingplatform_admin.UpdateUserGroupMemberRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> marketingplatform_admin.SetPropertyServiceLevelResponse: - r"""Call the set property service - level method over HTTP. + ) -> resources.UserGroupMember: + r"""Call the update user group member method over HTTP. - Args: - request (~.marketingplatform_admin.SetPropertyServiceLevelRequest): - The request object. Request message for - SetPropertyServiceLevel RPC. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. + Args: + request (~.marketingplatform_admin.UpdateUserGroupMemberRequest): + The request object. Request message for + UpdateUserGroupMember RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. - Returns: - ~.marketingplatform_admin.SetPropertyServiceLevelResponse: - Response message for - SetPropertyServiceLevel RPC. + Returns: + ~.resources.UserGroupMember: + A resource message representing a + member of a user group. """ - http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseSetPropertyServiceLevel._get_http_options() - request, metadata = self._interceptor.pre_set_property_service_level( + http_options = _BaseMarketingplatformAdminServiceRestTransport._BaseUpdateUserGroupMember._get_http_options() + request, metadata = self._interceptor.pre_update_user_group_member( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseMarketingplatformAdminServiceRestTransport._BaseSetPropertyServiceLevel, - "_BaseSetPropertyServiceLevel__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseMarketingplatformAdminServiceRestTransport._BaseUpdateUserGroupMember, + "_BaseUpdateUserGroupMember__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -1754,17 +4533,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.SetPropertyServiceLevel", + f"Sending request for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.UpdateUserGroupMember", extra={ "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", - "rpcName": "SetPropertyServiceLevel", + "rpcName": "UpdateUserGroupMember", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = MarketingplatformAdminServiceRestTransport._SetPropertyServiceLevel._get_response( + response = MarketingplatformAdminServiceRestTransport._UpdateUserGroupMember._get_response( self._host, metadata, query_params, @@ -1780,25 +4559,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = marketingplatform_admin.SetPropertyServiceLevelResponse() - pb_resp = marketingplatform_admin.SetPropertyServiceLevelResponse.pb(resp) + resp = resources.UserGroupMember() + pb_resp = resources.UserGroupMember.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_property_service_level(resp) + resp = self._interceptor.post_update_user_group_member(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_set_property_service_level_with_metadata( + resp, _ = self._interceptor.post_update_user_group_member_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - marketingplatform_admin.SetPropertyServiceLevelResponse.to_json( - response - ) - ) + response_payload = resources.UserGroupMember.to_json(response) except: response_payload = None http_response = { @@ -1807,16 +4582,29 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.set_property_service_level", + "Received response for google.marketingplatform.admin_v1alpha.MarketingplatformAdminServiceClient.update_user_group_member", extra={ "serviceName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", - "rpcName": "SetPropertyServiceLevel", + "rpcName": "UpdateUserGroupMember", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp + @property + def create_admin_access_binding( + self, + ) -> Callable[ + [marketingplatform_admin.CreateAdminAccessBindingRequest], + resources.AdminAccessBinding, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateAdminAccessBinding( + self._session, self._host, self._interceptor + ) # type: ignore + @property def create_analytics_account_link( self, @@ -1830,6 +4618,27 @@ def create_analytics_account_link( self._session, self._host, self._interceptor ) # type: ignore + @property + def create_user_group( + self, + ) -> Callable[ + [marketingplatform_admin.CreateUserGroupRequest], resources.UserGroup + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateUserGroup(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_user_group_member( + self, + ) -> Callable[ + [marketingplatform_admin.CreateUserGroupMemberRequest], + resources.UserGroupMember, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateUserGroupMember(self._session, self._host, self._interceptor) # type: ignore + @property def delete_analytics_account_link( self, @@ -1842,6 +4651,24 @@ def delete_analytics_account_link( self._session, self._host, self._interceptor ) # type: ignore + @property + def delete_user_group( + self, + ) -> Callable[[marketingplatform_admin.DeleteUserGroupRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteUserGroup(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_user_group_member( + self, + ) -> Callable[ + [marketingplatform_admin.DeleteUserGroupMemberRequest], empty_pb2.Empty + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteUserGroupMember(self._session, self._host, self._interceptor) # type: ignore + @property def find_sales_partner_managed_clients( self, @@ -1855,6 +4682,17 @@ def find_sales_partner_managed_clients( self._session, self._host, self._interceptor ) # type: ignore + @property + def get_admin_access_binding( + self, + ) -> Callable[ + [marketingplatform_admin.GetAdminAccessBindingRequest], + resources.AdminAccessBinding, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAdminAccessBinding(self._session, self._host, self._interceptor) # type: ignore + @property def get_organization( self, @@ -1865,6 +4703,37 @@ def get_organization( # In C++ this would require a dynamic_cast return self._GetOrganization(self._session, self._host, self._interceptor) # type: ignore + @property + def get_user_group( + self, + ) -> Callable[[marketingplatform_admin.GetUserGroupRequest], resources.UserGroup]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetUserGroup(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_user_group_member( + self, + ) -> Callable[ + [marketingplatform_admin.GetUserGroupMemberRequest], resources.UserGroupMember + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetUserGroupMember(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_admin_access_bindings( + self, + ) -> Callable[ + [marketingplatform_admin.ListAdminAccessBindingsRequest], + marketingplatform_admin.ListAdminAccessBindingsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAdminAccessBindings( + self._session, self._host, self._interceptor + ) # type: ignore + @property def list_analytics_account_links( self, @@ -1889,6 +4758,28 @@ def list_organizations( # In C++ this would require a dynamic_cast return self._ListOrganizations(self._session, self._host, self._interceptor) # type: ignore + @property + def list_user_group_members( + self, + ) -> Callable[ + [marketingplatform_admin.ListUserGroupMembersRequest], + marketingplatform_admin.ListUserGroupMembersResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListUserGroupMembers(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_user_groups( + self, + ) -> Callable[ + [marketingplatform_admin.ListUserGroupsRequest], + marketingplatform_admin.ListUserGroupsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListUserGroups(self._session, self._host, self._interceptor) # type: ignore + @property def report_property_usage( self, @@ -1913,6 +4804,40 @@ def set_property_service_level( self._session, self._host, self._interceptor ) # type: ignore + @property + def update_admin_access_binding( + self, + ) -> Callable[ + [marketingplatform_admin.UpdateAdminAccessBindingRequest], + resources.AdminAccessBinding, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateAdminAccessBinding( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_user_group( + self, + ) -> Callable[ + [marketingplatform_admin.UpdateUserGroupRequest], resources.UserGroup + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateUserGroup(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_user_group_member( + self, + ) -> Callable[ + [marketingplatform_admin.UpdateUserGroupMemberRequest], + resources.UserGroupMember, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateUserGroupMember(self._session, self._host, self._interceptor) # type: ignore + @property def kind(self) -> str: return "rest" diff --git a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/rest_base.py b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/rest_base.py index 74b0c06640ba..8edf50e5c81d 100644 --- a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/rest_base.py +++ b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/services/marketingplatform_admin_service/transports/rest_base.py @@ -93,6 +93,23 @@ def __init__( api_audience=api_audience, ) + class _BaseCreateAdminAccessBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=organizations/*}/adminAccessBindings", + "body": "admin_access_binding", + }, + ] + return http_options + class _BaseCreateAnalyticsAccountLink: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -110,6 +127,40 @@ def _get_http_options(): ] return http_options + class _BaseCreateUserGroup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=organizations/*}/userGroups", + "body": "user_group", + }, + ] + return http_options + + class _BaseCreateUserGroupMember: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=organizations/*/userGroups/*}/members", + "body": "user_group_member", + }, + ] + return http_options + class _BaseDeleteAnalyticsAccountLink: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -126,6 +177,38 @@ def _get_http_options(): ] return http_options + class _BaseDeleteUserGroup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1alpha/{name=organizations/*/userGroups/*}", + }, + ] + return http_options + + class _BaseDeleteUserGroupMember: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1alpha/{name=organizations/*/userGroups/*/members/*}", + }, + ] + return http_options + class _BaseFindSalesPartnerManagedClients: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -143,6 +226,22 @@ def _get_http_options(): ] return http_options + class _BaseGetAdminAccessBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=organizations/*/adminAccessBindings/*}", + }, + ] + return http_options + class _BaseGetOrganization: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -159,6 +258,54 @@ def _get_http_options(): ] return http_options + class _BaseGetUserGroup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=organizations/*/userGroups/*}", + }, + ] + return http_options + + class _BaseGetUserGroupMember: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=organizations/*/userGroups/*/members/*}", + }, + ] + return http_options + + class _BaseListAdminAccessBindings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=organizations/*}/adminAccessBindings", + }, + ] + return http_options + class _BaseListAnalyticsAccountLinks: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -189,6 +336,38 @@ def _get_http_options(): ] return http_options + class _BaseListUserGroupMembers: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=organizations/*/userGroups/*}/members", + }, + ] + return http_options + + class _BaseListUserGroups: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=organizations/*}/userGroups", + }, + ] + return http_options + class _BaseReportPropertyUsage: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -223,5 +402,62 @@ def _get_http_options(): ] return http_options + class _BaseUpdateAdminAccessBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1alpha/{admin_access_binding.name=organizations/*/adminAccessBindings/*}", + "body": "admin_access_binding", + }, + ] + return http_options + + class _BaseUpdateUserGroup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1alpha/{user_group.name=organizations/*/userGroups/*}", + "body": "user_group", + }, + ] + return http_options + + class _BaseUpdateUserGroupMember: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1alpha/{user_group_member.name=organizations/*/userGroups/*/members/*}", + "body": "user_group_member", + }, + ] + return http_options + __all__ = ("_BaseMarketingplatformAdminServiceRestTransport",) diff --git a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/types/__init__.py b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/types/__init__.py index bf313932e954..f043cbb71a25 100644 --- a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/types/__init__.py +++ b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/types/__init__.py @@ -14,45 +14,87 @@ # limitations under the License. # from .marketingplatform_admin import ( + CreateAdminAccessBindingRequest, CreateAnalyticsAccountLinkRequest, + CreateUserGroupMemberRequest, + CreateUserGroupRequest, DeleteAnalyticsAccountLinkRequest, + DeleteUserGroupMemberRequest, + DeleteUserGroupRequest, FindSalesPartnerManagedClientsRequest, FindSalesPartnerManagedClientsResponse, + GetAdminAccessBindingRequest, GetOrganizationRequest, + GetUserGroupMemberRequest, + GetUserGroupRequest, + ListAdminAccessBindingsRequest, + ListAdminAccessBindingsResponse, ListAnalyticsAccountLinksRequest, ListAnalyticsAccountLinksResponse, ListOrganizationsRequest, ListOrganizationsResponse, + ListUserGroupMembersRequest, + ListUserGroupMembersResponse, + ListUserGroupsRequest, + ListUserGroupsResponse, ReportPropertyUsageRequest, ReportPropertyUsageResponse, SetPropertyServiceLevelRequest, SetPropertyServiceLevelResponse, + UpdateAdminAccessBindingRequest, + UpdateUserGroupMemberRequest, + UpdateUserGroupRequest, ) from .resources import ( + AdminAccessBinding, AnalyticsAccountLink, AnalyticsPropertyType, AnalyticsServiceLevel, LinkVerificationState, Organization, + OrganizationRole, + UserGroup, + UserGroupMember, ) __all__ = ( + "CreateAdminAccessBindingRequest", "CreateAnalyticsAccountLinkRequest", + "CreateUserGroupMemberRequest", + "CreateUserGroupRequest", "DeleteAnalyticsAccountLinkRequest", + "DeleteUserGroupMemberRequest", + "DeleteUserGroupRequest", "FindSalesPartnerManagedClientsRequest", "FindSalesPartnerManagedClientsResponse", + "GetAdminAccessBindingRequest", "GetOrganizationRequest", + "GetUserGroupMemberRequest", + "GetUserGroupRequest", + "ListAdminAccessBindingsRequest", + "ListAdminAccessBindingsResponse", "ListAnalyticsAccountLinksRequest", "ListAnalyticsAccountLinksResponse", "ListOrganizationsRequest", "ListOrganizationsResponse", + "ListUserGroupMembersRequest", + "ListUserGroupMembersResponse", + "ListUserGroupsRequest", + "ListUserGroupsResponse", "ReportPropertyUsageRequest", "ReportPropertyUsageResponse", "SetPropertyServiceLevelRequest", "SetPropertyServiceLevelResponse", + "UpdateAdminAccessBindingRequest", + "UpdateUserGroupMemberRequest", + "UpdateUserGroupRequest", + "AdminAccessBinding", "AnalyticsAccountLink", "Organization", + "UserGroup", + "UserGroupMember", "AnalyticsPropertyType", "AnalyticsServiceLevel", "LinkVerificationState", + "OrganizationRole", ) diff --git a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/types/marketingplatform_admin.py b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/types/marketingplatform_admin.py index d93532d5c2a1..f8a61497d5da 100644 --- a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/types/marketingplatform_admin.py +++ b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/types/marketingplatform_admin.py @@ -17,6 +17,7 @@ from typing import MutableMapping, MutableSequence +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.type.date_pb2 as date_pb2 # type: ignore import google.type.money_pb2 as money_pb2 # type: ignore import proto # type: ignore @@ -39,6 +40,23 @@ "SetPropertyServiceLevelResponse", "ReportPropertyUsageRequest", "ReportPropertyUsageResponse", + "GetUserGroupRequest", + "ListUserGroupsRequest", + "ListUserGroupsResponse", + "CreateUserGroupRequest", + "UpdateUserGroupRequest", + "DeleteUserGroupRequest", + "GetUserGroupMemberRequest", + "ListUserGroupMembersRequest", + "ListUserGroupMembersResponse", + "CreateUserGroupMemberRequest", + "UpdateUserGroupMemberRequest", + "DeleteUserGroupMemberRequest", + "GetAdminAccessBindingRequest", + "ListAdminAccessBindingsRequest", + "ListAdminAccessBindingsResponse", + "CreateAdminAccessBindingRequest", + "UpdateAdminAccessBindingRequest", }, ) @@ -480,4 +498,430 @@ class BillInfo(proto.Message): ) +class GetUserGroupRequest(proto.Message): + r"""Request message for GetUserGroup RPC. + + Attributes: + name (str): + Required. The name of the UserGroup to retrieve. Format: + organizations/{org_id}/userGroups/{user_group_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListUserGroupsRequest(proto.Message): + r"""Request message for ListUserGroups RPC. + + Attributes: + parent (str): + Required. The parent org where this UserGroup will be + listed. Format: organizations/{org_id} + page_size (int): + Optional. The maximum number of user groups + to return in one call. The service may return + fewer than this value. + + If unspecified, at most 50 user groups will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + Optional. A page token, received from a previous + ListUserGroups call. Provide this to retrieve the subsequent + page. + + When paginating, all other parameters provided to + ``ListUserGroups`` must match the call that provided the + page token. + """ + + 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 ListUserGroupsResponse(proto.Message): + r"""Response message for ListUserGroups RPC. + + Attributes: + user_groups (MutableSequence[google.ads.marketingplatform_admin_v1alpha.types.UserGroup]): + User groups in the organization. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + user_groups: MutableSequence[resources.UserGroup] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.UserGroup, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateUserGroupRequest(proto.Message): + r"""Request message for CreateUserGroup RPC. + + Attributes: + parent (str): + Required. The parent resource where this UserGroup will be + created. Format: organizations/{org_id} + user_group (google.ads.marketingplatform_admin_v1alpha.types.UserGroup): + Required. The user group to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_group: resources.UserGroup = proto.Field( + proto.MESSAGE, + number=2, + message=resources.UserGroup, + ) + + +class UpdateUserGroupRequest(proto.Message): + r"""Request message for UpdateUserGroup RPC. + + Attributes: + user_group (google.ads.marketingplatform_admin_v1alpha.types.UserGroup): + Required. The user group to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. Field names must be + in snake case (for example, "field_to_update"). Omitted + fields will not be updated. To replace the entire entity, + use one path with the string "\*" to match all fields. + """ + + user_group: resources.UserGroup = proto.Field( + proto.MESSAGE, + number=1, + message=resources.UserGroup, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteUserGroupRequest(proto.Message): + r"""Request message for DeleteUserGroup RPC. + + Attributes: + name (str): + Required. The name of the user group to delete. Format: + organizations/{org_id}/userGroups/{user_group_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetUserGroupMemberRequest(proto.Message): + r"""Request message for GetUserGroupMember RPC. + + Attributes: + name (str): + Required. The name of the user group member to retrieve. + Format: + organizations/{org_id}/userGroups/{user_group_id}/members/{member_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListUserGroupMembersRequest(proto.Message): + r"""Request message for ListUserGroupMembers RPC. + + Attributes: + parent (str): + Required. The parent user group where this UserGroupMember + will be listed. Format: + organizations/{org_id}/userGroups/{user_group_id} + page_size (int): + Optional. The maximum number of user group + members to return in one call. The service may + return fewer than this value. + + If unspecified, at most 50 user group members + will be returned. The maximum value is 1000; + values above 1000 will be coerced to 1000. + page_token (str): + Optional. A page token, received from a previous + ListUserGroupMembers call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListUserGroupMembers`` must match the call that provided + the page token. + """ + + 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 ListUserGroupMembersResponse(proto.Message): + r"""Response message for ListUserGroupMembers RPC. + + Attributes: + user_group_members (MutableSequence[google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember]): + User group members in the user group. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + user_group_members: MutableSequence[resources.UserGroupMember] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.UserGroupMember, + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateUserGroupMemberRequest(proto.Message): + r"""Request message for CreateUserGroupMember RPC. + + Attributes: + parent (str): + Required. The parent resource where this UserGroupMember + will be created. Format: + organizations/{org_id}/userGroups/{user_group_id} + user_group_member (google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember): + Required. The user group member to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_group_member: resources.UserGroupMember = proto.Field( + proto.MESSAGE, + number=2, + message=resources.UserGroupMember, + ) + + +class UpdateUserGroupMemberRequest(proto.Message): + r"""Request message for UpdateUserGroupMember RPC. + + Attributes: + user_group_member (google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember): + Required. The user group member to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. Field names must be + in snake case (for example, "field_to_update"). Omitted + fields will not be updated. To replace the entire entity, + use one path with the string "\*" to match all fields. + """ + + user_group_member: resources.UserGroupMember = proto.Field( + proto.MESSAGE, + number=1, + message=resources.UserGroupMember, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteUserGroupMemberRequest(proto.Message): + r"""Request message for DeleteUserGroupMember RPC. + + Attributes: + name (str): + Required. The name of the user group member to delete. + Format: + organizations/{org_id}/userGroups/{user_group_id}/members/{member_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetAdminAccessBindingRequest(proto.Message): + r"""Response message for GetAdminAccessBinding RPC. + + Attributes: + name (str): + Required. The name of the AdminAccessBinding to retrieve. + Format: + organizations/{org_id}/adminAccessBindings/{admin_access_binding_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAdminAccessBindingsRequest(proto.Message): + r"""Request message for ListAdminAccessBindings RPC. + + Attributes: + parent (str): + Required. The parent organization, which owns this + collection of Admin Access Bindings. Format: + organizations/{org_id} + page_size (int): + Optional. The maximum number of Admin Access + Bindings to return in one call. The service may + return fewer than this value. + + If unspecified, at most 50 Admin Access Bindings + will be returned. The maximum value is 1000; + values above 1000 will be coerced to 1000. + page_token (str): + Optional. A page token, received from a previous + ListAdminAccessBindings call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListAdminAccessBindings`` must match the call that + provided the page token. + """ + + 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 ListAdminAccessBindingsResponse(proto.Message): + r"""Response message for ListAdminAccessBindings RPC. + + Attributes: + admin_access_bindings (MutableSequence[google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding]): + Admin Access Bindings in the organization. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + admin_access_bindings: MutableSequence[resources.AdminAccessBinding] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.AdminAccessBinding, + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateAdminAccessBindingRequest(proto.Message): + r"""Request message for CreateAdminAccessBinding RPC. + + Attributes: + parent (str): + Required. The parent organization, which owns this Admin + Access Binding. Format: organizations/{org_id} + admin_access_binding (google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding): + Required. The Admin Access Binding to create. + + Only 'user_email' input is allowed. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + admin_access_binding: resources.AdminAccessBinding = proto.Field( + proto.MESSAGE, + number=2, + message=resources.AdminAccessBinding, + ) + + +class UpdateAdminAccessBindingRequest(proto.Message): + r"""Request message for UpdateAdminAccessBinding RPC. + + Attributes: + admin_access_binding (google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding): + Required. The AdminAccessBinding to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. Field names must be + in snake case (for example, "field_to_update"). Omitted + fields will not be updated. To replace the entire entity, + use one path with the string "\*" to match all fields. + """ + + admin_access_binding: resources.AdminAccessBinding = proto.Field( + proto.MESSAGE, + number=1, + message=resources.AdminAccessBinding, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/types/resources.py b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/types/resources.py index b95c2c721a06..c6ae7567dc33 100644 --- a/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/types/resources.py +++ b/packages/google-ads-marketingplatform-admin/google/ads/marketingplatform_admin_v1alpha/types/resources.py @@ -25,8 +25,12 @@ "LinkVerificationState", "AnalyticsServiceLevel", "AnalyticsPropertyType", + "OrganizationRole", "Organization", "AnalyticsAccountLink", + "UserGroup", + "UserGroupMember", + "AdminAccessBinding", }, ) @@ -87,6 +91,32 @@ class AnalyticsPropertyType(proto.Enum): ANALYTICS_PROPERTY_TYPE_ROLLUP = 3 +class OrganizationRole(proto.Enum): + r"""Roles that can be assigned to a user or user group in a GMP + organization. + + Values: + ORGANIZATION_ROLE_UNSPECIFIED (0): + Unknown or unspecified organization role. + ORG_ADMIN_ROLE (1): + Organization admin role that grants all + administrative privileges. + USER_ADMIN_ROLE (2): + User admin role that grants access to the + Users section to perform various user management + functions. + BILLING_ADMIN_ROLE (3): + Billing admin role that grants access to the + Billing section to perform various + billing-related functions. + """ + + ORGANIZATION_ROLE_UNSPECIFIED = 0 + ORG_ADMIN_ROLE = 1 + USER_ADMIN_ROLE = 2 + BILLING_ADMIN_ROLE = 3 + + class Organization(proto.Message): r"""A resource message representing a Google Marketing Platform organization. @@ -157,4 +187,161 @@ class AnalyticsAccountLink(proto.Message): ) +class UserGroup(proto.Message): + r"""A resource message representing a user group in a GMP + organization. + + Attributes: + name (str): + Identifier. Resource name of this UserGroup. + + Format: organizations/{org_id}/userGroups/{user_group_id} + Example: "organizations/123abc/userGroups/456def". + display_name (str): + Optional. The human-readable name for the + user group. + description (str): + Optional. The description of the user group. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UserGroupMember(proto.Message): + r"""A resource message representing a member of a user group. + + 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: + user_email (str): + Email address of the user member. + + This field is a member of `oneof`_ ``member``. + user_group (str): + User group resource name of the group member. + + This field is a member of `oneof`_ ``member``. + name (str): + Identifier. The resource name of this UserGroupMember. + + Format: + organizations/{org_id}/userGroups/{user_group_id}/members/{member_id} + Example: + "organizations/123abc/userGroups/456def/members/789ghi". + membership_role (google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember.MembershipRole): + Optional. The role of the member in the user + group. + """ + + class MembershipRole(proto.Enum): + r"""The role of the member in the user group. + + Values: + MEMBERSHIP_ROLE_UNSPECIFIED (0): + Unspecified membership role. + MEMBERSHIP_ROLE_OWNER (1): + Owner role that can add and remove group + members. + MEMBERSHIP_ROLE_MEMBER (2): + Member role that receives all permissions + assigned to the group. + """ + + MEMBERSHIP_ROLE_UNSPECIFIED = 0 + MEMBERSHIP_ROLE_OWNER = 1 + MEMBERSHIP_ROLE_MEMBER = 2 + + user_email: str = proto.Field( + proto.STRING, + number=2, + oneof="member", + ) + user_group: str = proto.Field( + proto.STRING, + number=3, + oneof="member", + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + membership_role: MembershipRole = proto.Field( + proto.ENUM, + number=4, + enum=MembershipRole, + ) + + +class AdminAccessBinding(proto.Message): + r"""A resource message representing a binding to a set of roles. + + 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: + user_email (str): + Email address of the user. + + This field is a member of `oneof`_ ``access_target``. + user_group (str): + Resource name of the user group. + + This field is a member of `oneof`_ ``access_target``. + name (str): + Identifier. The resource name of this AdminAccessBinding. + + Format: + organizations/{org_id}/adminAccessBindings/{admin_access_binding_id} + Example: "organizations/123abc/adminAccessBindings/456def". + organization_roles (MutableSequence[google.ads.marketingplatform_admin_v1alpha.types.OrganizationRole]): + Optional. A list of roles granted to the parent + organization. + + USER_ADMIN_ROLE and BILLING_ADMIN_ROLE will be automatically + added if ORG_ADMIN_ROLE is assigned. + + No roles will be assigned if no roles are specified. + """ + + user_email: str = proto.Field( + proto.STRING, + number=2, + oneof="access_target", + ) + user_group: str = proto.Field( + proto.STRING, + number=3, + oneof="access_target", + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + organization_roles: MutableSequence["OrganizationRole"] = proto.RepeatedField( + proto.ENUM, + number=4, + enum="OrganizationRole", + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_admin_access_binding_async.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_admin_access_binding_async.py new file mode 100644 index 000000000000..0994c080ad5d --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_admin_access_binding_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAdminAccessBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateAdminAccessBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +async def sample_create_admin_access_binding(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + admin_access_binding = marketingplatform_admin_v1alpha.AdminAccessBinding() + admin_access_binding.user_email = "user_email_value" + + request = marketingplatform_admin_v1alpha.CreateAdminAccessBindingRequest( + parent="parent_value", + admin_access_binding=admin_access_binding, + ) + + # Make the request + response = await client.create_admin_access_binding(request=request) + + # Handle the response + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateAdminAccessBinding_async] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_admin_access_binding_sync.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_admin_access_binding_sync.py new file mode 100644 index 000000000000..5d57240c7d82 --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_admin_access_binding_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAdminAccessBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateAdminAccessBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +def sample_create_admin_access_binding(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + admin_access_binding = marketingplatform_admin_v1alpha.AdminAccessBinding() + admin_access_binding.user_email = "user_email_value" + + request = marketingplatform_admin_v1alpha.CreateAdminAccessBindingRequest( + parent="parent_value", + admin_access_binding=admin_access_binding, + ) + + # Make the request + response = client.create_admin_access_binding(request=request) + + # Handle the response + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateAdminAccessBinding_sync] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_async.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_async.py new file mode 100644 index 000000000000..3f005e08193e --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateUserGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateUserGroup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +async def sample_create_user_group(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.CreateUserGroupRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_user_group(request=request) + + # Handle the response + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateUserGroup_async] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_member_async.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_member_async.py new file mode 100644 index 000000000000..74f883d657bb --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_member_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateUserGroupMember +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateUserGroupMember_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +async def sample_create_user_group_member(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + user_group_member = marketingplatform_admin_v1alpha.UserGroupMember() + user_group_member.user_email = "user_email_value" + + request = marketingplatform_admin_v1alpha.CreateUserGroupMemberRequest( + parent="parent_value", + user_group_member=user_group_member, + ) + + # Make the request + response = await client.create_user_group_member(request=request) + + # Handle the response + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateUserGroupMember_async] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_member_sync.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_member_sync.py new file mode 100644 index 000000000000..7edb8e495820 --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_member_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateUserGroupMember +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateUserGroupMember_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +def sample_create_user_group_member(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + user_group_member = marketingplatform_admin_v1alpha.UserGroupMember() + user_group_member.user_email = "user_email_value" + + request = marketingplatform_admin_v1alpha.CreateUserGroupMemberRequest( + parent="parent_value", + user_group_member=user_group_member, + ) + + # Make the request + response = client.create_user_group_member(request=request) + + # Handle the response + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateUserGroupMember_sync] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_sync.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_sync.py new file mode 100644 index 000000000000..a366edc69171 --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateUserGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateUserGroup_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +def sample_create_user_group(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.CreateUserGroupRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_user_group(request=request) + + # Handle the response + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateUserGroup_sync] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_async.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_async.py new file mode 100644 index 000000000000..fceb52c174cf --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUserGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_DeleteUserGroup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +async def sample_delete_user_group(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.DeleteUserGroupRequest( + name="name_value", + ) + + # Make the request + await client.delete_user_group(request=request) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_DeleteUserGroup_async] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_member_async.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_member_async.py new file mode 100644 index 000000000000..ca285e6f0cc5 --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_member_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUserGroupMember +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_DeleteUserGroupMember_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +async def sample_delete_user_group_member(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.DeleteUserGroupMemberRequest( + name="name_value", + ) + + # Make the request + await client.delete_user_group_member(request=request) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_DeleteUserGroupMember_async] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_member_sync.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_member_sync.py new file mode 100644 index 000000000000..b11f09b230bf --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_member_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUserGroupMember +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_DeleteUserGroupMember_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +def sample_delete_user_group_member(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.DeleteUserGroupMemberRequest( + name="name_value", + ) + + # Make the request + client.delete_user_group_member(request=request) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_DeleteUserGroupMember_sync] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_sync.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_sync.py new file mode 100644 index 000000000000..b8cc5f7ec1c4 --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUserGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_DeleteUserGroup_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +def sample_delete_user_group(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.DeleteUserGroupRequest( + name="name_value", + ) + + # Make the request + client.delete_user_group(request=request) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_DeleteUserGroup_sync] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_admin_access_binding_async.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_admin_access_binding_async.py new file mode 100644 index 000000000000..1d36f382aa2d --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_admin_access_binding_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAdminAccessBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetAdminAccessBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +async def sample_get_admin_access_binding(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.GetAdminAccessBindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_admin_access_binding(request=request) + + # Handle the response + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetAdminAccessBinding_async] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_admin_access_binding_sync.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_admin_access_binding_sync.py new file mode 100644 index 000000000000..a2d916160e02 --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_admin_access_binding_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAdminAccessBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetAdminAccessBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +def sample_get_admin_access_binding(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.GetAdminAccessBindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_admin_access_binding(request=request) + + # Handle the response + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetAdminAccessBinding_sync] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_async.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_async.py new file mode 100644 index 000000000000..6cc228027bcf --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetUserGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetUserGroup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +async def sample_get_user_group(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.GetUserGroupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user_group(request=request) + + # Handle the response + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetUserGroup_async] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_member_async.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_member_async.py new file mode 100644 index 000000000000..70030f234199 --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_member_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetUserGroupMember +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetUserGroupMember_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +async def sample_get_user_group_member(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.GetUserGroupMemberRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user_group_member(request=request) + + # Handle the response + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetUserGroupMember_async] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_member_sync.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_member_sync.py new file mode 100644 index 000000000000..2d7003f3b0e4 --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_member_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetUserGroupMember +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetUserGroupMember_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +def sample_get_user_group_member(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.GetUserGroupMemberRequest( + name="name_value", + ) + + # Make the request + response = client.get_user_group_member(request=request) + + # Handle the response + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetUserGroupMember_sync] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_sync.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_sync.py new file mode 100644 index 000000000000..e139365520f9 --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetUserGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetUserGroup_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +def sample_get_user_group(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.GetUserGroupRequest( + name="name_value", + ) + + # Make the request + response = client.get_user_group(request=request) + + # Handle the response + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetUserGroup_sync] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_admin_access_bindings_async.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_admin_access_bindings_async.py new file mode 100644 index 000000000000..e39b9ccd64fc --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_admin_access_bindings_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAdminAccessBindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListAdminAccessBindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +async def sample_list_admin_access_bindings(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.ListAdminAccessBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_admin_access_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListAdminAccessBindings_async] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_admin_access_bindings_sync.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_admin_access_bindings_sync.py new file mode 100644 index 000000000000..730c7cda1dc3 --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_admin_access_bindings_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAdminAccessBindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListAdminAccessBindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +def sample_list_admin_access_bindings(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.ListAdminAccessBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_admin_access_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListAdminAccessBindings_sync] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_group_members_async.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_group_members_async.py new file mode 100644 index 000000000000..51e71a8d8fc9 --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_group_members_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUserGroupMembers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListUserGroupMembers_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +async def sample_list_user_group_members(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.ListUserGroupMembersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_group_members(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListUserGroupMembers_async] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_group_members_sync.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_group_members_sync.py new file mode 100644 index 000000000000..8c1fb3f850c6 --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_group_members_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUserGroupMembers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListUserGroupMembers_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +def sample_list_user_group_members(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.ListUserGroupMembersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_group_members(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListUserGroupMembers_sync] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_groups_async.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_groups_async.py new file mode 100644 index 000000000000..aa64e6f01c8d --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_groups_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUserGroups +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListUserGroups_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +async def sample_list_user_groups(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.ListUserGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_groups(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListUserGroups_async] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_groups_sync.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_groups_sync.py new file mode 100644 index 000000000000..958668093505 --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_groups_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUserGroups +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListUserGroups_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +def sample_list_user_groups(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.ListUserGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_groups(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListUserGroups_sync] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_admin_access_binding_async.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_admin_access_binding_async.py new file mode 100644 index 000000000000..d3d06fb101da --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_admin_access_binding_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAdminAccessBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_UpdateAdminAccessBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +async def sample_update_admin_access_binding(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + admin_access_binding = marketingplatform_admin_v1alpha.AdminAccessBinding() + admin_access_binding.user_email = "user_email_value" + + request = marketingplatform_admin_v1alpha.UpdateAdminAccessBindingRequest( + admin_access_binding=admin_access_binding, + ) + + # Make the request + response = await client.update_admin_access_binding(request=request) + + # Handle the response + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_UpdateAdminAccessBinding_async] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_admin_access_binding_sync.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_admin_access_binding_sync.py new file mode 100644 index 000000000000..6b76d68c8810 --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_admin_access_binding_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAdminAccessBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_UpdateAdminAccessBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +def sample_update_admin_access_binding(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + admin_access_binding = marketingplatform_admin_v1alpha.AdminAccessBinding() + admin_access_binding.user_email = "user_email_value" + + request = marketingplatform_admin_v1alpha.UpdateAdminAccessBindingRequest( + admin_access_binding=admin_access_binding, + ) + + # Make the request + response = client.update_admin_access_binding(request=request) + + # Handle the response + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_UpdateAdminAccessBinding_sync] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_async.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_async.py new file mode 100644 index 000000000000..1e42971f142a --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUserGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_UpdateUserGroup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +async def sample_update_user_group(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.UpdateUserGroupRequest() + + # Make the request + response = await client.update_user_group(request=request) + + # Handle the response + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_UpdateUserGroup_async] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_member_async.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_member_async.py new file mode 100644 index 000000000000..2079eabe4e25 --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_member_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUserGroupMember +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_UpdateUserGroupMember_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +async def sample_update_user_group_member(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient() + + # Initialize request argument(s) + user_group_member = marketingplatform_admin_v1alpha.UserGroupMember() + user_group_member.user_email = "user_email_value" + + request = marketingplatform_admin_v1alpha.UpdateUserGroupMemberRequest( + user_group_member=user_group_member, + ) + + # Make the request + response = await client.update_user_group_member(request=request) + + # Handle the response + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_UpdateUserGroupMember_async] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_member_sync.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_member_sync.py new file mode 100644 index 000000000000..9fed2156ecf4 --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_member_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUserGroupMember +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_UpdateUserGroupMember_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +def sample_update_user_group_member(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + user_group_member = marketingplatform_admin_v1alpha.UserGroupMember() + user_group_member.user_email = "user_email_value" + + request = marketingplatform_admin_v1alpha.UpdateUserGroupMemberRequest( + user_group_member=user_group_member, + ) + + # Make the request + response = client.update_user_group_member(request=request) + + # Handle the response + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_UpdateUserGroupMember_sync] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_sync.py b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_sync.py new file mode 100644 index 000000000000..8443c8816884 --- /dev/null +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUserGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-marketingplatform-admin + + +# [START marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_UpdateUserGroup_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.ads import marketingplatform_admin_v1alpha + + +def sample_update_user_group(): + # Create a client + client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient() + + # Initialize request argument(s) + request = marketingplatform_admin_v1alpha.UpdateUserGroupRequest() + + # Make the request + response = client.update_user_group(request=request) + + # Handle the response + print(response) + + +# [END marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_UpdateUserGroup_sync] diff --git a/packages/google-ads-marketingplatform-admin/samples/generated_samples/snippet_metadata_google.marketingplatform.admin.v1alpha.json b/packages/google-ads-marketingplatform-admin/samples/generated_samples/snippet_metadata_google.marketingplatform.admin.v1alpha.json index 34b849094d4b..202a2da9a9b1 100644 --- a/packages/google-ads-marketingplatform-admin/samples/generated_samples/snippet_metadata_google.marketingplatform.admin.v1alpha.json +++ b/packages/google-ads-marketingplatform-admin/samples/generated_samples/snippet_metadata_google.marketingplatform.admin.v1alpha.json @@ -19,27 +19,27 @@ "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", "shortName": "MarketingplatformAdminServiceAsyncClient" }, - "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.create_analytics_account_link", + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.create_admin_access_binding", "method": { - "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.CreateAnalyticsAccountLink", + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.CreateAdminAccessBinding", "service": { "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", "shortName": "MarketingplatformAdminService" }, - "shortName": "CreateAnalyticsAccountLink" + "shortName": "CreateAdminAccessBinding" }, "parameters": [ { "name": "request", - "type": "google.ads.marketingplatform_admin_v1alpha.types.CreateAnalyticsAccountLinkRequest" + "type": "google.ads.marketingplatform_admin_v1alpha.types.CreateAdminAccessBindingRequest" }, { "name": "parent", "type": "str" }, { - "name": "analytics_account_link", - "type": "google.ads.marketingplatform_admin_v1alpha.types.AnalyticsAccountLink" + "name": "admin_access_binding", + "type": "google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding" }, { "name": "retry", @@ -54,14 +54,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.marketingplatform_admin_v1alpha.types.AnalyticsAccountLink", - "shortName": "create_analytics_account_link" + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding", + "shortName": "create_admin_access_binding" }, - "description": "Sample for CreateAnalyticsAccountLink", - "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_analytics_account_link_async.py", + "description": "Sample for CreateAdminAccessBinding", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_admin_access_binding_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateAnalyticsAccountLink_async", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateAdminAccessBinding_async", "segments": [ { "end": 55, @@ -94,7 +94,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_analytics_account_link_async.py" + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_admin_access_binding_async.py" }, { "canonical": true, @@ -103,27 +103,27 @@ "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", "shortName": "MarketingplatformAdminServiceClient" }, - "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.create_analytics_account_link", + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.create_admin_access_binding", "method": { - "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.CreateAnalyticsAccountLink", + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.CreateAdminAccessBinding", "service": { "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", "shortName": "MarketingplatformAdminService" }, - "shortName": "CreateAnalyticsAccountLink" + "shortName": "CreateAdminAccessBinding" }, "parameters": [ { "name": "request", - "type": "google.ads.marketingplatform_admin_v1alpha.types.CreateAnalyticsAccountLinkRequest" + "type": "google.ads.marketingplatform_admin_v1alpha.types.CreateAdminAccessBindingRequest" }, { "name": "parent", "type": "str" }, { - "name": "analytics_account_link", - "type": "google.ads.marketingplatform_admin_v1alpha.types.AnalyticsAccountLink" + "name": "admin_access_binding", + "type": "google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding" }, { "name": "retry", @@ -138,14 +138,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.marketingplatform_admin_v1alpha.types.AnalyticsAccountLink", - "shortName": "create_analytics_account_link" + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding", + "shortName": "create_admin_access_binding" }, - "description": "Sample for CreateAnalyticsAccountLink", - "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_analytics_account_link_sync.py", + "description": "Sample for CreateAdminAccessBinding", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_admin_access_binding_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateAnalyticsAccountLink_sync", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateAdminAccessBinding_sync", "segments": [ { "end": 55, @@ -178,7 +178,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_analytics_account_link_sync.py" + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_admin_access_binding_sync.py" }, { "canonical": true, @@ -188,24 +188,28 @@ "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", "shortName": "MarketingplatformAdminServiceAsyncClient" }, - "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.delete_analytics_account_link", + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.create_analytics_account_link", "method": { - "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.DeleteAnalyticsAccountLink", + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.CreateAnalyticsAccountLink", "service": { "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", "shortName": "MarketingplatformAdminService" }, - "shortName": "DeleteAnalyticsAccountLink" + "shortName": "CreateAnalyticsAccountLink" }, "parameters": [ { "name": "request", - "type": "google.ads.marketingplatform_admin_v1alpha.types.DeleteAnalyticsAccountLinkRequest" + "type": "google.ads.marketingplatform_admin_v1alpha.types.CreateAnalyticsAccountLinkRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "analytics_account_link", + "type": "google.ads.marketingplatform_admin_v1alpha.types.AnalyticsAccountLink" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -219,21 +223,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_analytics_account_link" + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.AnalyticsAccountLink", + "shortName": "create_analytics_account_link" }, - "description": "Sample for DeleteAnalyticsAccountLink", - "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_analytics_account_link_async.py", + "description": "Sample for CreateAnalyticsAccountLink", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_analytics_account_link_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_DeleteAnalyticsAccountLink_async", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateAnalyticsAccountLink_async", "segments": [ { - "end": 49, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 55, "start": 27, "type": "SHORT" }, @@ -243,20 +248,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 46, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_analytics_account_link_async.py" + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_analytics_account_link_async.py" }, { "canonical": true, @@ -265,24 +272,28 @@ "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", "shortName": "MarketingplatformAdminServiceClient" }, - "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.delete_analytics_account_link", + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.create_analytics_account_link", "method": { - "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.DeleteAnalyticsAccountLink", + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.CreateAnalyticsAccountLink", "service": { "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", "shortName": "MarketingplatformAdminService" }, - "shortName": "DeleteAnalyticsAccountLink" + "shortName": "CreateAnalyticsAccountLink" }, "parameters": [ { "name": "request", - "type": "google.ads.marketingplatform_admin_v1alpha.types.DeleteAnalyticsAccountLinkRequest" + "type": "google.ads.marketingplatform_admin_v1alpha.types.CreateAnalyticsAccountLinkRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "analytics_account_link", + "type": "google.ads.marketingplatform_admin_v1alpha.types.AnalyticsAccountLink" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -296,21 +307,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_analytics_account_link" + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.AnalyticsAccountLink", + "shortName": "create_analytics_account_link" }, - "description": "Sample for DeleteAnalyticsAccountLink", - "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_analytics_account_link_sync.py", + "description": "Sample for CreateAnalyticsAccountLink", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_analytics_account_link_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_DeleteAnalyticsAccountLink_sync", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateAnalyticsAccountLink_sync", "segments": [ { - "end": 49, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 55, "start": 27, "type": "SHORT" }, @@ -320,20 +332,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 46, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_analytics_account_link_sync.py" + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_analytics_account_link_sync.py" }, { "canonical": true, @@ -343,19 +357,27 @@ "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", "shortName": "MarketingplatformAdminServiceAsyncClient" }, - "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.find_sales_partner_managed_clients", + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.create_user_group_member", "method": { - "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.FindSalesPartnerManagedClients", + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.CreateUserGroupMember", "service": { "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", "shortName": "MarketingplatformAdminService" }, - "shortName": "FindSalesPartnerManagedClients" + "shortName": "CreateUserGroupMember" }, "parameters": [ { "name": "request", - "type": "google.ads.marketingplatform_admin_v1alpha.types.FindSalesPartnerManagedClientsRequest" + "type": "google.ads.marketingplatform_admin_v1alpha.types.CreateUserGroupMemberRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user_group_member", + "type": "google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember" }, { "name": "retry", @@ -370,22 +392,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.marketingplatform_admin_v1alpha.types.FindSalesPartnerManagedClientsResponse", - "shortName": "find_sales_partner_managed_clients" + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember", + "shortName": "create_user_group_member" }, - "description": "Sample for FindSalesPartnerManagedClients", - "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_find_sales_partner_managed_clients_async.py", + "description": "Sample for CreateUserGroupMember", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_member_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_FindSalesPartnerManagedClients_async", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateUserGroupMember_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -395,22 +417,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_find_sales_partner_managed_clients_async.py" + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_member_async.py" }, { "canonical": true, @@ -419,19 +441,27 @@ "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", "shortName": "MarketingplatformAdminServiceClient" }, - "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.find_sales_partner_managed_clients", + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.create_user_group_member", "method": { - "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.FindSalesPartnerManagedClients", + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.CreateUserGroupMember", "service": { "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", "shortName": "MarketingplatformAdminService" }, - "shortName": "FindSalesPartnerManagedClients" + "shortName": "CreateUserGroupMember" }, "parameters": [ { "name": "request", - "type": "google.ads.marketingplatform_admin_v1alpha.types.FindSalesPartnerManagedClientsRequest" + "type": "google.ads.marketingplatform_admin_v1alpha.types.CreateUserGroupMemberRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user_group_member", + "type": "google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember" }, { "name": "retry", @@ -446,22 +476,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.marketingplatform_admin_v1alpha.types.FindSalesPartnerManagedClientsResponse", - "shortName": "find_sales_partner_managed_clients" + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember", + "shortName": "create_user_group_member" }, - "description": "Sample for FindSalesPartnerManagedClients", - "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_find_sales_partner_managed_clients_sync.py", + "description": "Sample for CreateUserGroupMember", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_member_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_FindSalesPartnerManagedClients_sync", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateUserGroupMember_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -471,22 +501,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_find_sales_partner_managed_clients_sync.py" + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_member_sync.py" }, { "canonical": true, @@ -496,24 +526,28 @@ "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", "shortName": "MarketingplatformAdminServiceAsyncClient" }, - "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.get_organization", + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.create_user_group", "method": { - "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.GetOrganization", + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.CreateUserGroup", "service": { "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", "shortName": "MarketingplatformAdminService" }, - "shortName": "GetOrganization" + "shortName": "CreateUserGroup" }, "parameters": [ { "name": "request", - "type": "google.ads.marketingplatform_admin_v1alpha.types.GetOrganizationRequest" + "type": "google.ads.marketingplatform_admin_v1alpha.types.CreateUserGroupRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "user_group", + "type": "google.ads.marketingplatform_admin_v1alpha.types.UserGroup" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -527,14 +561,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.marketingplatform_admin_v1alpha.types.Organization", - "shortName": "get_organization" + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.UserGroup", + "shortName": "create_user_group" }, - "description": "Sample for GetOrganization", - "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_organization_async.py", + "description": "Sample for CreateUserGroup", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetOrganization_async", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateUserGroup_async", "segments": [ { "end": 51, @@ -567,7 +601,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_organization_async.py" + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_async.py" }, { "canonical": true, @@ -576,24 +610,28 @@ "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", "shortName": "MarketingplatformAdminServiceClient" }, - "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.get_organization", + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.create_user_group", "method": { - "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.GetOrganization", + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.CreateUserGroup", "service": { "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", "shortName": "MarketingplatformAdminService" }, - "shortName": "GetOrganization" + "shortName": "CreateUserGroup" }, "parameters": [ { "name": "request", - "type": "google.ads.marketingplatform_admin_v1alpha.types.GetOrganizationRequest" + "type": "google.ads.marketingplatform_admin_v1alpha.types.CreateUserGroupRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "user_group", + "type": "google.ads.marketingplatform_admin_v1alpha.types.UserGroup" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -607,14 +645,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.marketingplatform_admin_v1alpha.types.Organization", - "shortName": "get_organization" + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.UserGroup", + "shortName": "create_user_group" }, - "description": "Sample for GetOrganization", - "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_organization_sync.py", + "description": "Sample for CreateUserGroup", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetOrganization_sync", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_CreateUserGroup_sync", "segments": [ { "end": 51, @@ -647,7 +685,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_organization_sync.py" + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_create_user_group_sync.py" }, { "canonical": true, @@ -657,22 +695,22 @@ "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", "shortName": "MarketingplatformAdminServiceAsyncClient" }, - "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.list_analytics_account_links", + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.delete_analytics_account_link", "method": { - "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.ListAnalyticsAccountLinks", + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.DeleteAnalyticsAccountLink", "service": { "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", "shortName": "MarketingplatformAdminService" }, - "shortName": "ListAnalyticsAccountLinks" + "shortName": "DeleteAnalyticsAccountLink" }, "parameters": [ { "name": "request", - "type": "google.ads.marketingplatform_admin_v1alpha.types.ListAnalyticsAccountLinksRequest" + "type": "google.ads.marketingplatform_admin_v1alpha.types.DeleteAnalyticsAccountLinkRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -688,22 +726,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListAnalyticsAccountLinksAsyncPager", - "shortName": "list_analytics_account_links" + "shortName": "delete_analytics_account_link" }, - "description": "Sample for ListAnalyticsAccountLinks", - "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_analytics_account_links_async.py", + "description": "Sample for DeleteAnalyticsAccountLink", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_analytics_account_link_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListAnalyticsAccountLinks_async", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_DeleteAnalyticsAccountLink_async", "segments": [ { - "end": 52, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 49, "start": 27, "type": "SHORT" }, @@ -718,17 +755,15 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_analytics_account_links_async.py" + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_analytics_account_link_async.py" }, { "canonical": true, @@ -737,22 +772,22 @@ "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", "shortName": "MarketingplatformAdminServiceClient" }, - "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.list_analytics_account_links", + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.delete_analytics_account_link", "method": { - "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.ListAnalyticsAccountLinks", + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.DeleteAnalyticsAccountLink", "service": { "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", "shortName": "MarketingplatformAdminService" }, - "shortName": "ListAnalyticsAccountLinks" + "shortName": "DeleteAnalyticsAccountLink" }, "parameters": [ { "name": "request", - "type": "google.ads.marketingplatform_admin_v1alpha.types.ListAnalyticsAccountLinksRequest" + "type": "google.ads.marketingplatform_admin_v1alpha.types.DeleteAnalyticsAccountLinkRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -768,22 +803,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListAnalyticsAccountLinksPager", - "shortName": "list_analytics_account_links" + "shortName": "delete_analytics_account_link" }, - "description": "Sample for ListAnalyticsAccountLinks", - "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_analytics_account_links_sync.py", + "description": "Sample for DeleteAnalyticsAccountLink", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_analytics_account_link_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListAnalyticsAccountLinks_sync", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_DeleteAnalyticsAccountLink_sync", "segments": [ { - "end": 52, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 49, "start": 27, "type": "SHORT" }, @@ -798,17 +832,15 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_analytics_account_links_sync.py" + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_analytics_account_link_sync.py" }, { "canonical": true, @@ -818,19 +850,23 @@ "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", "shortName": "MarketingplatformAdminServiceAsyncClient" }, - "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.list_organizations", + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.delete_user_group_member", "method": { - "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.ListOrganizations", + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.DeleteUserGroupMember", "service": { "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", "shortName": "MarketingplatformAdminService" }, - "shortName": "ListOrganizations" + "shortName": "DeleteUserGroupMember" }, "parameters": [ { "name": "request", - "type": "google.ads.marketingplatform_admin_v1alpha.types.ListOrganizationsRequest" + "type": "google.ads.marketingplatform_admin_v1alpha.types.DeleteUserGroupMemberRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -845,22 +881,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListOrganizationsAsyncPager", - "shortName": "list_organizations" + "shortName": "delete_user_group_member" }, - "description": "Sample for ListOrganizations", - "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_organizations_async.py", + "description": "Sample for DeleteUserGroupMember", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_member_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListOrganizations_async", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_DeleteUserGroupMember_async", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -870,22 +905,20 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 48, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_organizations_async.py" + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_member_async.py" }, { "canonical": true, @@ -894,19 +927,23 @@ "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", "shortName": "MarketingplatformAdminServiceClient" }, - "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.list_organizations", + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.delete_user_group_member", "method": { - "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.ListOrganizations", + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.DeleteUserGroupMember", "service": { "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", "shortName": "MarketingplatformAdminService" }, - "shortName": "ListOrganizations" + "shortName": "DeleteUserGroupMember" }, "parameters": [ { "name": "request", - "type": "google.ads.marketingplatform_admin_v1alpha.types.ListOrganizationsRequest" + "type": "google.ads.marketingplatform_admin_v1alpha.types.DeleteUserGroupMemberRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -921,22 +958,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListOrganizationsPager", - "shortName": "list_organizations" + "shortName": "delete_user_group_member" }, - "description": "Sample for ListOrganizations", - "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_organizations_sync.py", + "description": "Sample for DeleteUserGroupMember", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_member_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListOrganizations_sync", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_DeleteUserGroupMember_sync", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -946,22 +982,20 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 48, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_organizations_sync.py" + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_member_sync.py" }, { "canonical": true, @@ -971,22 +1005,22 @@ "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", "shortName": "MarketingplatformAdminServiceAsyncClient" }, - "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.report_property_usage", + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.delete_user_group", "method": { - "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.ReportPropertyUsage", + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.DeleteUserGroup", "service": { "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", "shortName": "MarketingplatformAdminService" }, - "shortName": "ReportPropertyUsage" + "shortName": "DeleteUserGroup" }, "parameters": [ { "name": "request", - "type": "google.ads.marketingplatform_admin_v1alpha.types.ReportPropertyUsageRequest" + "type": "google.ads.marketingplatform_admin_v1alpha.types.DeleteUserGroupRequest" }, { - "name": "organization", + "name": "name", "type": "str" }, { @@ -1002,22 +1036,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.marketingplatform_admin_v1alpha.types.ReportPropertyUsageResponse", - "shortName": "report_property_usage" + "shortName": "delete_user_group" }, - "description": "Sample for ReportPropertyUsage", - "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_report_property_usage_async.py", + "description": "Sample for DeleteUserGroup", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ReportPropertyUsage_async", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_DeleteUserGroup_async", "segments": [ { - "end": 52, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 49, "start": 27, "type": "SHORT" }, @@ -1027,22 +1060,20 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_report_property_usage_async.py" + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_async.py" }, { "canonical": true, @@ -1051,22 +1082,22 @@ "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", "shortName": "MarketingplatformAdminServiceClient" }, - "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.report_property_usage", + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.delete_user_group", "method": { - "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.ReportPropertyUsage", + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.DeleteUserGroup", "service": { "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", "shortName": "MarketingplatformAdminService" }, - "shortName": "ReportPropertyUsage" + "shortName": "DeleteUserGroup" }, "parameters": [ { "name": "request", - "type": "google.ads.marketingplatform_admin_v1alpha.types.ReportPropertyUsageRequest" + "type": "google.ads.marketingplatform_admin_v1alpha.types.DeleteUserGroupRequest" }, { - "name": "organization", + "name": "name", "type": "str" }, { @@ -1082,22 +1113,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.marketingplatform_admin_v1alpha.types.ReportPropertyUsageResponse", - "shortName": "report_property_usage" + "shortName": "delete_user_group" }, - "description": "Sample for ReportPropertyUsage", - "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_report_property_usage_sync.py", + "description": "Sample for DeleteUserGroup", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ReportPropertyUsage_sync", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_DeleteUserGroup_sync", "segments": [ { - "end": 52, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 49, "start": 27, "type": "SHORT" }, @@ -1107,22 +1137,20 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_report_property_usage_sync.py" + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_delete_user_group_sync.py" }, { "canonical": true, @@ -1132,23 +1160,19 @@ "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", "shortName": "MarketingplatformAdminServiceAsyncClient" }, - "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.set_property_service_level", + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.find_sales_partner_managed_clients", "method": { - "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.SetPropertyServiceLevel", + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.FindSalesPartnerManagedClients", "service": { "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", "shortName": "MarketingplatformAdminService" }, - "shortName": "SetPropertyServiceLevel" + "shortName": "FindSalesPartnerManagedClients" }, "parameters": [ { "name": "request", - "type": "google.ads.marketingplatform_admin_v1alpha.types.SetPropertyServiceLevelRequest" - }, - { - "name": "analytics_account_link", - "type": "str" + "type": "google.ads.marketingplatform_admin_v1alpha.types.FindSalesPartnerManagedClientsRequest" }, { "name": "retry", @@ -1163,22 +1187,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.marketingplatform_admin_v1alpha.types.SetPropertyServiceLevelResponse", - "shortName": "set_property_service_level" + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.FindSalesPartnerManagedClientsResponse", + "shortName": "find_sales_partner_managed_clients" }, - "description": "Sample for SetPropertyServiceLevel", - "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_set_property_service_level_async.py", + "description": "Sample for FindSalesPartnerManagedClients", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_find_sales_partner_managed_clients_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_SetPropertyServiceLevel_async", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_FindSalesPartnerManagedClients_async", "segments": [ { - "end": 53, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1188,22 +1212,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_set_property_service_level_async.py" + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_find_sales_partner_managed_clients_async.py" }, { "canonical": true, @@ -1212,22 +1236,99 @@ "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", "shortName": "MarketingplatformAdminServiceClient" }, - "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.set_property_service_level", + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.find_sales_partner_managed_clients", "method": { - "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.SetPropertyServiceLevel", + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.FindSalesPartnerManagedClients", "service": { "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", "shortName": "MarketingplatformAdminService" }, - "shortName": "SetPropertyServiceLevel" + "shortName": "FindSalesPartnerManagedClients" }, "parameters": [ { "name": "request", - "type": "google.ads.marketingplatform_admin_v1alpha.types.SetPropertyServiceLevelRequest" + "type": "google.ads.marketingplatform_admin_v1alpha.types.FindSalesPartnerManagedClientsRequest" }, { - "name": "analytics_account_link", + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.FindSalesPartnerManagedClientsResponse", + "shortName": "find_sales_partner_managed_clients" + }, + "description": "Sample for FindSalesPartnerManagedClients", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_find_sales_partner_managed_clients_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_FindSalesPartnerManagedClients_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": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_find_sales_partner_managed_clients_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", + "shortName": "MarketingplatformAdminServiceAsyncClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.get_admin_access_binding", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.GetAdminAccessBinding", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "GetAdminAccessBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.GetAdminAccessBindingRequest" + }, + { + "name": "name", "type": "str" }, { @@ -1243,22 +1344,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.marketingplatform_admin_v1alpha.types.SetPropertyServiceLevelResponse", - "shortName": "set_property_service_level" + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding", + "shortName": "get_admin_access_binding" }, - "description": "Sample for SetPropertyServiceLevel", - "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_set_property_service_level_sync.py", + "description": "Sample for GetAdminAccessBinding", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_admin_access_binding_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_SetPropertyServiceLevel_sync", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetAdminAccessBinding_async", "segments": [ { - "end": 53, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1268,22 +1369,2211 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_set_property_service_level_sync.py" + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_admin_access_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", + "shortName": "MarketingplatformAdminServiceClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.get_admin_access_binding", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.GetAdminAccessBinding", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "GetAdminAccessBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.GetAdminAccessBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding", + "shortName": "get_admin_access_binding" + }, + "description": "Sample for GetAdminAccessBinding", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_admin_access_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetAdminAccessBinding_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": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_admin_access_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", + "shortName": "MarketingplatformAdminServiceAsyncClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.get_organization", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.GetOrganization", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "GetOrganization" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.GetOrganizationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.Organization", + "shortName": "get_organization" + }, + "description": "Sample for GetOrganization", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_organization_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetOrganization_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_organization_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", + "shortName": "MarketingplatformAdminServiceClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.get_organization", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.GetOrganization", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "GetOrganization" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.GetOrganizationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.Organization", + "shortName": "get_organization" + }, + "description": "Sample for GetOrganization", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_organization_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetOrganization_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_organization_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", + "shortName": "MarketingplatformAdminServiceAsyncClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.get_user_group_member", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.GetUserGroupMember", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "GetUserGroupMember" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.GetUserGroupMemberRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember", + "shortName": "get_user_group_member" + }, + "description": "Sample for GetUserGroupMember", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_member_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetUserGroupMember_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": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_member_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", + "shortName": "MarketingplatformAdminServiceClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.get_user_group_member", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.GetUserGroupMember", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "GetUserGroupMember" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.GetUserGroupMemberRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember", + "shortName": "get_user_group_member" + }, + "description": "Sample for GetUserGroupMember", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_member_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetUserGroupMember_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": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_member_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", + "shortName": "MarketingplatformAdminServiceAsyncClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.get_user_group", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.GetUserGroup", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "GetUserGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.GetUserGroupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.UserGroup", + "shortName": "get_user_group" + }, + "description": "Sample for GetUserGroup", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetUserGroup_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": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", + "shortName": "MarketingplatformAdminServiceClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.get_user_group", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.GetUserGroup", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "GetUserGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.GetUserGroupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.UserGroup", + "shortName": "get_user_group" + }, + "description": "Sample for GetUserGroup", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_GetUserGroup_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": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_get_user_group_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", + "shortName": "MarketingplatformAdminServiceAsyncClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.list_admin_access_bindings", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.ListAdminAccessBindings", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "ListAdminAccessBindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.ListAdminAccessBindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListAdminAccessBindingsAsyncPager", + "shortName": "list_admin_access_bindings" + }, + "description": "Sample for ListAdminAccessBindings", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_admin_access_bindings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListAdminAccessBindings_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": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_admin_access_bindings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", + "shortName": "MarketingplatformAdminServiceClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.list_admin_access_bindings", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.ListAdminAccessBindings", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "ListAdminAccessBindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.ListAdminAccessBindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListAdminAccessBindingsPager", + "shortName": "list_admin_access_bindings" + }, + "description": "Sample for ListAdminAccessBindings", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_admin_access_bindings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListAdminAccessBindings_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": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_admin_access_bindings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", + "shortName": "MarketingplatformAdminServiceAsyncClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.list_analytics_account_links", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.ListAnalyticsAccountLinks", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "ListAnalyticsAccountLinks" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.ListAnalyticsAccountLinksRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListAnalyticsAccountLinksAsyncPager", + "shortName": "list_analytics_account_links" + }, + "description": "Sample for ListAnalyticsAccountLinks", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_analytics_account_links_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListAnalyticsAccountLinks_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": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_analytics_account_links_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", + "shortName": "MarketingplatformAdminServiceClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.list_analytics_account_links", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.ListAnalyticsAccountLinks", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "ListAnalyticsAccountLinks" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.ListAnalyticsAccountLinksRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListAnalyticsAccountLinksPager", + "shortName": "list_analytics_account_links" + }, + "description": "Sample for ListAnalyticsAccountLinks", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_analytics_account_links_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListAnalyticsAccountLinks_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": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_analytics_account_links_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", + "shortName": "MarketingplatformAdminServiceAsyncClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.list_organizations", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.ListOrganizations", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "ListOrganizations" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.ListOrganizationsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListOrganizationsAsyncPager", + "shortName": "list_organizations" + }, + "description": "Sample for ListOrganizations", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_organizations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListOrganizations_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_organizations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", + "shortName": "MarketingplatformAdminServiceClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.list_organizations", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.ListOrganizations", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "ListOrganizations" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.ListOrganizationsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListOrganizationsPager", + "shortName": "list_organizations" + }, + "description": "Sample for ListOrganizations", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_organizations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListOrganizations_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_organizations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", + "shortName": "MarketingplatformAdminServiceAsyncClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.list_user_group_members", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.ListUserGroupMembers", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "ListUserGroupMembers" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupMembersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListUserGroupMembersAsyncPager", + "shortName": "list_user_group_members" + }, + "description": "Sample for ListUserGroupMembers", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_group_members_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListUserGroupMembers_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": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_group_members_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", + "shortName": "MarketingplatformAdminServiceClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.list_user_group_members", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.ListUserGroupMembers", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "ListUserGroupMembers" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupMembersRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListUserGroupMembersPager", + "shortName": "list_user_group_members" + }, + "description": "Sample for ListUserGroupMembers", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_group_members_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListUserGroupMembers_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": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_group_members_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", + "shortName": "MarketingplatformAdminServiceAsyncClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.list_user_groups", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.ListUserGroups", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "ListUserGroups" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListUserGroupsAsyncPager", + "shortName": "list_user_groups" + }, + "description": "Sample for ListUserGroups", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_groups_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListUserGroups_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": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_groups_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", + "shortName": "MarketingplatformAdminServiceClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.list_user_groups", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.ListUserGroups", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "ListUserGroups" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.ListUserGroupsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.services.marketingplatform_admin_service.pagers.ListUserGroupsPager", + "shortName": "list_user_groups" + }, + "description": "Sample for ListUserGroups", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_groups_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ListUserGroups_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": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_list_user_groups_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", + "shortName": "MarketingplatformAdminServiceAsyncClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.report_property_usage", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.ReportPropertyUsage", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "ReportPropertyUsage" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.ReportPropertyUsageRequest" + }, + { + "name": "organization", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.ReportPropertyUsageResponse", + "shortName": "report_property_usage" + }, + "description": "Sample for ReportPropertyUsage", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_report_property_usage_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ReportPropertyUsage_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_report_property_usage_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", + "shortName": "MarketingplatformAdminServiceClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.report_property_usage", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.ReportPropertyUsage", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "ReportPropertyUsage" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.ReportPropertyUsageRequest" + }, + { + "name": "organization", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.ReportPropertyUsageResponse", + "shortName": "report_property_usage" + }, + "description": "Sample for ReportPropertyUsage", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_report_property_usage_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_ReportPropertyUsage_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_report_property_usage_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", + "shortName": "MarketingplatformAdminServiceAsyncClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.set_property_service_level", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.SetPropertyServiceLevel", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "SetPropertyServiceLevel" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.SetPropertyServiceLevelRequest" + }, + { + "name": "analytics_account_link", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.SetPropertyServiceLevelResponse", + "shortName": "set_property_service_level" + }, + "description": "Sample for SetPropertyServiceLevel", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_set_property_service_level_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_SetPropertyServiceLevel_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_set_property_service_level_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", + "shortName": "MarketingplatformAdminServiceClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.set_property_service_level", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.SetPropertyServiceLevel", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "SetPropertyServiceLevel" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.SetPropertyServiceLevelRequest" + }, + { + "name": "analytics_account_link", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.SetPropertyServiceLevelResponse", + "shortName": "set_property_service_level" + }, + "description": "Sample for SetPropertyServiceLevel", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_set_property_service_level_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_SetPropertyServiceLevel_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_set_property_service_level_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", + "shortName": "MarketingplatformAdminServiceAsyncClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.update_admin_access_binding", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.UpdateAdminAccessBinding", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "UpdateAdminAccessBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.UpdateAdminAccessBindingRequest" + }, + { + "name": "admin_access_binding", + "type": "google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding", + "shortName": "update_admin_access_binding" + }, + "description": "Sample for UpdateAdminAccessBinding", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_admin_access_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_UpdateAdminAccessBinding_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_admin_access_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", + "shortName": "MarketingplatformAdminServiceClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.update_admin_access_binding", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.UpdateAdminAccessBinding", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "UpdateAdminAccessBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.UpdateAdminAccessBindingRequest" + }, + { + "name": "admin_access_binding", + "type": "google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.AdminAccessBinding", + "shortName": "update_admin_access_binding" + }, + "description": "Sample for UpdateAdminAccessBinding", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_admin_access_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_UpdateAdminAccessBinding_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_admin_access_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", + "shortName": "MarketingplatformAdminServiceAsyncClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.update_user_group_member", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.UpdateUserGroupMember", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "UpdateUserGroupMember" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.UpdateUserGroupMemberRequest" + }, + { + "name": "user_group_member", + "type": "google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember", + "shortName": "update_user_group_member" + }, + "description": "Sample for UpdateUserGroupMember", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_member_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_UpdateUserGroupMember_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_member_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", + "shortName": "MarketingplatformAdminServiceClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.update_user_group_member", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.UpdateUserGroupMember", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "UpdateUserGroupMember" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.UpdateUserGroupMemberRequest" + }, + { + "name": "user_group_member", + "type": "google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.UserGroupMember", + "shortName": "update_user_group_member" + }, + "description": "Sample for UpdateUserGroupMember", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_member_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_UpdateUserGroupMember_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_member_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient", + "shortName": "MarketingplatformAdminServiceAsyncClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceAsyncClient.update_user_group", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.UpdateUserGroup", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "UpdateUserGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.UpdateUserGroupRequest" + }, + { + "name": "user_group", + "type": "google.ads.marketingplatform_admin_v1alpha.types.UserGroup" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.UserGroup", + "shortName": "update_user_group" + }, + "description": "Sample for UpdateUserGroup", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_UpdateUserGroup_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient", + "shortName": "MarketingplatformAdminServiceClient" + }, + "fullName": "google.ads.marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient.update_user_group", + "method": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService.UpdateUserGroup", + "service": { + "fullName": "google.marketingplatform.admin.v1alpha.MarketingplatformAdminService", + "shortName": "MarketingplatformAdminService" + }, + "shortName": "UpdateUserGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.marketingplatform_admin_v1alpha.types.UpdateUserGroupRequest" + }, + { + "name": "user_group", + "type": "google.ads.marketingplatform_admin_v1alpha.types.UserGroup" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.marketingplatform_admin_v1alpha.types.UserGroup", + "shortName": "update_user_group" + }, + "description": "Sample for UpdateUserGroup", + "file": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "marketingplatformadmin_v1alpha_generated_MarketingplatformAdminService_UpdateUserGroup_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "marketingplatformadmin_v1alpha_generated_marketingplatform_admin_service_update_user_group_sync.py" } ] } diff --git a/packages/google-ads-marketingplatform-admin/tests/unit/gapic/marketingplatform_admin_v1alpha/test_marketingplatform_admin_service.py b/packages/google-ads-marketingplatform-admin/tests/unit/gapic/marketingplatform_admin_v1alpha/test_marketingplatform_admin_service.py index 3ddf6bf9e6e8..fbf6218151db 100644 --- a/packages/google-ads-marketingplatform-admin/tests/unit/gapic/marketingplatform_admin_v1alpha/test_marketingplatform_admin_service.py +++ b/packages/google-ads-marketingplatform-admin/tests/unit/gapic/marketingplatform_admin_v1alpha/test_marketingplatform_admin_service.py @@ -39,6 +39,7 @@ HAS_GOOGLE_AUTH_AIO = False import google.auth +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore from google.api_core import ( client_options, gapic_v1, @@ -4049,13 +4050,82 @@ async def test_report_property_usage_flattened_error_async(): ) -def test_get_organization_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.GetUserGroupRequest(), + {}, + ], +) +def test_get_user_group(request_type, transport: str = "grpc"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_user_group), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.UserGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + response = client.get_user_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.GetUserGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.UserGroup) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_get_user_group_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = marketingplatform_admin.GetUserGroupRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_user_group), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_user_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.GetUserGroupRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_user_group_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -4063,275 +4133,325 @@ def test_get_organization_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_organization in client._transport._wrapped_methods + assert client._transport.get_user_group in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_organization] = ( - mock_rpc - ) - + client._transport._wrapped_methods[client._transport.get_user_group] = mock_rpc request = {} - client.get_organization(request) + client.get_user_group(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_organization(request) + client.get_user_group(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_organization_rest_required_fields( - request_type=marketingplatform_admin.GetOrganizationRequest, +@pytest.mark.asyncio +async def test_get_user_group_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.MarketingplatformAdminServiceRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.get_user_group + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseGetOrganization, - "_BaseGetOrganization__REQUIRED_FIELDS_DEFAULT_VALUES", + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_user_group + ] = mock_rpc + + request = {} + await client.get_user_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_user_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.GetUserGroupRequest(), {}, + ], +) +async def test_get_user_group_async(request_type, transport: str = "grpc_asyncio"): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - jsonified_request["name"] = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_user_group), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.UserGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + ) + response = await client.get_user_group(request) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.GetUserGroupRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, resources.UserGroup) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_get_user_group_field_headers(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.Organization() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result - response_value = Response() - response_value.status_code = 200 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.GetUserGroupRequest() - # Convert return value to protobuf type - return_value = resources.Organization.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + request.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_user_group), "__call__") as call: + call.return_value = resources.UserGroup() + client.get_user_group(request) - response = client.get_organization(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -def test_get_organization_rest_flattened(): - client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_get_user_group_field_headers_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = resources.Organization() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "organizations/sample1"} + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.GetUserGroupRequest() - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + request.name = "name_value" - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.Organization.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_user_group), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.UserGroup()) + await client.get_user_group(request) - client.get_organization(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{name=organizations/*}" % client.transport._host, args[1] - ) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -def test_get_organization_rest_flattened_error(transport: str = "rest"): +def test_get_user_group_flattened(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_organization( - marketingplatform_admin.GetOrganizationRequest(), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_user_group), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.UserGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_user_group( 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_list_organizations_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +def test_get_user_group_flattened_error(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) - # Ensure method has been cached - assert ( - client._transport.list_organizations in client._transport._wrapped_methods + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_user_group( + marketingplatform_admin.GetUserGroupRequest(), + name="name_value", ) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.list_organizations] = ( - mock_rpc + +@pytest.mark.asyncio +async def test_get_user_group_flattened_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_user_group), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.UserGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.UserGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_user_group( + name="name_value", ) - request = {} - client.list_organizations(request) + # Establish that 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 - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - client.list_organizations(request) +@pytest.mark.asyncio +async def test_get_user_group_flattened_error_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_user_group( + marketingplatform_admin.GetUserGroupRequest(), + name="name_value", + ) -def test_list_organizations_rest_pager(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.ListUserGroupsRequest(), + {}, + ], +) +def test_list_user_groups(request_type, transport: str = "grpc"): client = MarketingplatformAdminServiceClient( 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 = ( - marketingplatform_admin.ListOrganizationsResponse( - organizations=[ - resources.Organization(), - resources.Organization(), - resources.Organization(), - ], - next_page_token="abc", - ), - marketingplatform_admin.ListOrganizationsResponse( - organizations=[], - next_page_token="def", - ), - marketingplatform_admin.ListOrganizationsResponse( - organizations=[ - resources.Organization(), - ], - next_page_token="ghi", - ), - marketingplatform_admin.ListOrganizationsResponse( - organizations=[ - resources.Organization(), - resources.Organization(), - ], - ), - ) - # Two responses for two calls - response = response + response + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - # Wrap the values into proper Response objs - response = tuple( - marketingplatform_admin.ListOrganizationsResponse.to_json(x) - for x in response + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_user_groups), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = marketingplatform_admin.ListUserGroupsResponse( + next_page_token="next_page_token_value", ) - 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 + response = client.list_user_groups(request) - sample_request = {} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.ListUserGroupsRequest() + assert args[0] == request - pager = client.list_organizations(request=sample_request) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserGroupsPager) + assert response.next_page_token == "next_page_token_value" - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Organization) for i in results) +def test_list_user_groups_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - pages = list(client.list_organizations(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = marketingplatform_admin.ListUserGroupsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_user_groups), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_user_groups(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.ListUserGroupsRequest( + parent="parent_value", + page_token="page_token_value", + ) + assert args[0] == request_msg -def test_find_sales_partner_managed_clients_rest_use_cached_wrapped_rpc(): +def test_list_user_groups_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -4339,373 +4459,528 @@ def test_find_sales_partner_managed_clients_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.find_sales_partner_managed_clients - in client._transport._wrapped_methods - ) + assert client._transport.list_user_groups in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.find_sales_partner_managed_clients - ] = mock_rpc - + client._transport._wrapped_methods[client._transport.list_user_groups] = ( + mock_rpc + ) request = {} - client.find_sales_partner_managed_clients(request) + client.list_user_groups(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.find_sales_partner_managed_clients(request) + client.list_user_groups(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_find_sales_partner_managed_clients_rest_required_fields( - request_type=marketingplatform_admin.FindSalesPartnerManagedClientsRequest, +@pytest.mark.asyncio +async def test_list_user_groups_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.MarketingplatformAdminServiceRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["organization"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.list_user_groups + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseFindSalesPartnerManagedClients, - "_BaseFindSalesPartnerManagedClients__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_user_groups + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.list_user_groups(request) - jsonified_request["organization"] = "organization_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # verify required fields with non-default values are left alone - assert "organization" in jsonified_request - assert jsonified_request["organization"] == "organization_value" + await client.list_user_groups(request) - client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Designate an appropriate value for the returned response. - return_value = marketingplatform_admin.FindSalesPartnerManagedClientsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = ( - marketingplatform_admin.FindSalesPartnerManagedClientsResponse.pb( - return_value - ) - ) - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.ListUserGroupsRequest(), + {}, + ], +) +async def test_list_user_groups_async(request_type, transport: str = "grpc_asyncio"): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - response = client.find_sales_partner_managed_clients(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_user_groups), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + marketingplatform_admin.ListUserGroupsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_user_groups(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.ListUserGroupsRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserGroupsAsyncPager) + assert response.next_page_token == "next_page_token_value" -def test_list_analytics_account_links_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +def test_list_user_groups_field_headers(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) - # Ensure method has been cached - assert ( - client._transport.list_analytics_account_links - in client._transport._wrapped_methods - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.ListUserGroupsRequest() - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_analytics_account_links - ] = mock_rpc + request.parent = "parent_value" - request = {} - client.list_analytics_account_links(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_user_groups), "__call__") as call: + call.return_value = marketingplatform_admin.ListUserGroupsResponse() + client.list_user_groups(request) # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_analytics_account_links(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + assert len(call.mock_calls) == 1 + _, args, _ = call.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_analytics_account_links_rest_required_fields( - request_type=marketingplatform_admin.ListAnalyticsAccountLinksRequest, -): - transport_class = transports.MarketingplatformAdminServiceRestTransport - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +@pytest.mark.asyncio +async def test_list_user_groups_field_headers_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - # verify fields with default values are dropped + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.ListUserGroupsRequest() - default_values = getattr( - transport_class._BaseListAnalyticsAccountLinks, - "_BaseListAnalyticsAccountLinks__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) + request.parent = "parent_value" - # verify required fields with default values are now present + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_user_groups), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + marketingplatform_admin.ListUserGroupsResponse() + ) + await client.list_user_groups(request) - jsonified_request["parent"] = "parent_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "pageSize", - "pageToken", - ) - ) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" +def test_list_user_groups_flattened(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = marketingplatform_admin.ListAnalyticsAccountLinksResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = marketingplatform_admin.ListAnalyticsAccountLinksResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_analytics_account_links(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_user_groups), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = marketingplatform_admin.ListUserGroupsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_user_groups( + parent="parent_value", + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the 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_analytics_account_links_rest_flattened(): +def test_list_user_groups_flattened_error(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = marketingplatform_admin.ListAnalyticsAccountLinksResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "organizations/sample1"} - - # get truthy value for each flattened field - mock_args = dict( + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_user_groups( + marketingplatform_admin.ListUserGroupsRequest(), parent="parent_value", ) - mock_args.update(sample_request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = marketingplatform_admin.ListAnalyticsAccountLinksResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_analytics_account_links(**mock_args) +@pytest.mark.asyncio +async def test_list_user_groups_flattened_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_user_groups), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = marketingplatform_admin.ListUserGroupsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + marketingplatform_admin.ListUserGroupsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_user_groups( + parent="parent_value", + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{parent=organizations/*}/analyticsAccountLinks" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -def test_list_analytics_account_links_rest_flattened_error(transport: str = "rest"): - client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_list_user_groups_flattened_error_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_analytics_account_links( - marketingplatform_admin.ListAnalyticsAccountLinksRequest(), + await client.list_user_groups( + marketingplatform_admin.ListUserGroupsRequest(), parent="parent_value", ) -def test_list_analytics_account_links_rest_pager(transport: str = "rest"): +def test_list_user_groups_pager(transport_name: str = "grpc"): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # 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 = ( - marketingplatform_admin.ListAnalyticsAccountLinksResponse( - analytics_account_links=[ - resources.AnalyticsAccountLink(), - resources.AnalyticsAccountLink(), - resources.AnalyticsAccountLink(), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_user_groups), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[ + resources.UserGroup(), + resources.UserGroup(), + resources.UserGroup(), ], next_page_token="abc", ), - marketingplatform_admin.ListAnalyticsAccountLinksResponse( - analytics_account_links=[], + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[], next_page_token="def", ), - marketingplatform_admin.ListAnalyticsAccountLinksResponse( - analytics_account_links=[ - resources.AnalyticsAccountLink(), + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[ + resources.UserGroup(), ], next_page_token="ghi", ), - marketingplatform_admin.ListAnalyticsAccountLinksResponse( - analytics_account_links=[ - resources.AnalyticsAccountLink(), - resources.AnalyticsAccountLink(), + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[ + resources.UserGroup(), + resources.UserGroup(), ], ), + RuntimeError, ) - # Two responses for two calls - response = response + response - # Wrap the values into proper Response objs - response = tuple( - marketingplatform_admin.ListAnalyticsAccountLinksResponse.to_json(x) - for x in response + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - 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": "organizations/sample1"} + pager = client.list_user_groups(request={}, retry=retry, timeout=timeout) - pager = client.list_analytics_account_links(request=sample_request) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resources.AnalyticsAccountLink) for i in results) + assert all(isinstance(i, resources.UserGroup) for i in results) - pages = list(client.list_analytics_account_links(request=sample_request).pages) + +def test_list_user_groups_pages(transport_name: str = "grpc"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_user_groups), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[ + resources.UserGroup(), + resources.UserGroup(), + resources.UserGroup(), + ], + next_page_token="abc", + ), + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[], + next_page_token="def", + ), + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[ + resources.UserGroup(), + ], + next_page_token="ghi", + ), + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[ + resources.UserGroup(), + resources.UserGroup(), + ], + ), + RuntimeError, + ) + pages = list(client.list_user_groups(request={}).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_create_analytics_account_link_rest_use_cached_wrapped_rpc(): +@pytest.mark.asyncio +async def test_list_user_groups_async_pager(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_groups), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[ + resources.UserGroup(), + resources.UserGroup(), + resources.UserGroup(), + ], + next_page_token="abc", + ), + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[], + next_page_token="def", + ), + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[ + resources.UserGroup(), + ], + next_page_token="ghi", + ), + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[ + resources.UserGroup(), + resources.UserGroup(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_user_groups( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.UserGroup) for i in responses) + + +@pytest.mark.asyncio +async def test_list_user_groups_async_pages(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_groups), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[ + resources.UserGroup(), + resources.UserGroup(), + resources.UserGroup(), + ], + next_page_token="abc", + ), + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[], + next_page_token="def", + ), + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[ + resources.UserGroup(), + ], + next_page_token="ghi", + ), + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[ + resources.UserGroup(), + resources.UserGroup(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_user_groups(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", + [ + marketingplatform_admin.CreateUserGroupRequest(), + {}, + ], +) +def test_create_user_group(request_type, transport: str = "grpc"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.UserGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + response = client.create_user_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.CreateUserGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.UserGroup) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_create_user_group_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = marketingplatform_admin.CreateUserGroupRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_group), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_user_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.CreateUserGroupRequest( + parent="parent_value", + ) + assert args[0] == request_msg + + +def test_create_user_group_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -4713,176 +4988,349 @@ def test_create_analytics_account_link_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_analytics_account_link - in client._transport._wrapped_methods - ) + assert client._transport.create_user_group in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.create_analytics_account_link - ] = mock_rpc - + client._transport._wrapped_methods[client._transport.create_user_group] = ( + mock_rpc + ) request = {} - client.create_analytics_account_link(request) + client.create_user_group(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_analytics_account_link(request) + client.create_user_group(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_analytics_account_link_rest_required_fields( - request_type=marketingplatform_admin.CreateAnalyticsAccountLinkRequest, +@pytest.mark.asyncio +async def test_create_user_group_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.MarketingplatformAdminServiceRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.create_user_group + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseCreateAnalyticsAccountLink, - "_BaseCreateAnalyticsAccountLink__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_user_group + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.create_user_group(request) - jsonified_request["parent"] = "parent_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + await client.create_user_group(request) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.CreateUserGroupRequest(), + {}, + ], +) +async def test_create_user_group_async(request_type, transport: str = "grpc_asyncio"): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.UserGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + ) + response = await client.create_user_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.CreateUserGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.UserGroup) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_create_user_group_field_headers(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = resources.AnalyticsAccountLink() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force 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 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.CreateUserGroupRequest() - response_value = Response() - response_value.status_code = 200 + request.parent = "parent_value" - # Convert return value to protobuf type - return_value = resources.AnalyticsAccountLink.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_group), "__call__" + ) as call: + call.return_value = resources.UserGroup() + client.create_user_group(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - response = client.create_analytics_account_link(request) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +@pytest.mark.asyncio +async def test_create_user_group_field_headers_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) -def test_create_analytics_account_link_rest_flattened(): + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.CreateUserGroupRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_group), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.UserGroup()) + await client.create_user_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_user_group_flattened(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = resources.AnalyticsAccountLink() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.UserGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_user_group( + parent="parent_value", + user_group=resources.UserGroup(name="name_value"), + ) - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "organizations/sample1"} + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].user_group + mock_val = resources.UserGroup(name="name_value") + assert arg == mock_val - # get truthy value for each flattened field - mock_args = dict( + +def test_create_user_group_flattened_error(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_user_group( + marketingplatform_admin.CreateUserGroupRequest(), parent="parent_value", - analytics_account_link=resources.AnalyticsAccountLink(name="name_value"), + user_group=resources.UserGroup(name="name_value"), ) - mock_args.update(sample_request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.AnalyticsAccountLink.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_analytics_account_link(**mock_args) +@pytest.mark.asyncio +async def test_create_user_group_flattened_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.UserGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.UserGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_user_group( + parent="parent_value", + user_group=resources.UserGroup(name="name_value"), + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{parent=organizations/*}/analyticsAccountLinks" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].user_group + mock_val = resources.UserGroup(name="name_value") + assert arg == mock_val -def test_create_analytics_account_link_rest_flattened_error(transport: str = "rest"): - client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_create_user_group_flattened_error_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_analytics_account_link( - marketingplatform_admin.CreateAnalyticsAccountLinkRequest(), + await client.create_user_group( + marketingplatform_admin.CreateUserGroupRequest(), parent="parent_value", - analytics_account_link=resources.AnalyticsAccountLink(name="name_value"), + user_group=resources.UserGroup(name="name_value"), ) -def test_delete_analytics_account_link_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.UpdateUserGroupRequest(), + {}, + ], +) +def test_update_user_group(request_type, transport: str = "grpc"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.UserGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + response = client.update_user_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.UpdateUserGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.UserGroup) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_update_user_group_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = marketingplatform_admin.UpdateUserGroupRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_group), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_user_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.UpdateUserGroupRequest() + assert args[0] == request_msg + + +def test_update_user_group_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -4890,353 +5338,346 @@ def test_delete_analytics_account_link_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_analytics_account_link - in client._transport._wrapped_methods - ) + assert client._transport.update_user_group in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.delete_analytics_account_link - ] = mock_rpc - + client._transport._wrapped_methods[client._transport.update_user_group] = ( + mock_rpc + ) request = {} - client.delete_analytics_account_link(request) + client.update_user_group(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_analytics_account_link(request) + client.update_user_group(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_analytics_account_link_rest_required_fields( - request_type=marketingplatform_admin.DeleteAnalyticsAccountLinkRequest, +@pytest.mark.asyncio +async def test_update_user_group_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.MarketingplatformAdminServiceRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.update_user_group + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseDeleteAnalyticsAccountLink, - "_BaseDeleteAnalyticsAccountLink__REQUIRED_FIELDS_DEFAULT_VALUES", + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_user_group + ] = mock_rpc + + request = {} + await client.update_user_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_user_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.UpdateUserGroupRequest(), {}, + ], +) +async def test_update_user_group_async(request_type, transport: str = "grpc_asyncio"): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - jsonified_request["name"] = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.UserGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + ) + response = await client.update_user_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.UpdateUserGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.UserGroup) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_update_user_group_field_headers(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "delete", - "query_params": pb_request, - } - transcode.return_value = transcode_result + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.UpdateUserGroupRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = "" + request.user_group.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_group), "__call__" + ) as call: + call.return_value = resources.UserGroup() + client.update_user_group(request) - response = client.delete_analytics_account_link(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "user_group.name=name_value", + ) in kw["metadata"] -def test_delete_analytics_account_link_rest_flattened(): - client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_update_user_group_field_headers_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the http request call within the method and 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 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.UpdateUserGroupRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"name": "organizations/sample1/analyticsAccountLinks/sample2"} + request.user_group.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_group), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.UserGroup()) + await client.update_user_group(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.delete_analytics_account_link(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "user_group.name=name_value", + ) in kw["metadata"] + + +def test_update_user_group_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.UserGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_user_group( + user_group=resources.UserGroup(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(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{name=organizations/*/analyticsAccountLinks/*}" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].user_group + mock_val = resources.UserGroup(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_delete_analytics_account_link_rest_flattened_error(transport: str = "rest"): +def test_update_user_group_flattened_error(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.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_analytics_account_link( - marketingplatform_admin.DeleteAnalyticsAccountLinkRequest(), - name="name_value", + client.update_user_group( + marketingplatform_admin.UpdateUserGroupRequest(), + user_group=resources.UserGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_set_property_service_level_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.asyncio +async def test_update_user_group_flattened_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert ( - client._transport.set_property_service_level - in client._transport._wrapped_methods - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.UserGroup() - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.UserGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_user_group( + user_group=resources.UserGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - client._transport._wrapped_methods[ - client._transport.set_property_service_level - ] = mock_rpc - request = {} - client.set_property_service_level(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].user_group + mock_val = resources.UserGroup(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 - client.set_property_service_level(request) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_set_property_service_level_rest_required_fields( - request_type=marketingplatform_admin.SetPropertyServiceLevelRequest, -): - transport_class = transports.MarketingplatformAdminServiceRestTransport - - request_init = {} - request_init["analytics_account_link"] = "" - request_init["analytics_property"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - default_values = getattr( - transport_class._BaseSetPropertyServiceLevel, - "_BaseSetPropertyServiceLevel__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_update_user_group_flattened_error_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present - - jsonified_request["analyticsAccountLink"] = "analytics_account_link_value" - jsonified_request["analyticsProperty"] = "analytics_property_value" + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_user_group( + marketingplatform_admin.UpdateUserGroupRequest(), + user_group=resources.UserGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) - # verify required fields with non-default values are left alone - assert "analyticsAccountLink" in jsonified_request - assert jsonified_request["analyticsAccountLink"] == "analytics_account_link_value" - assert "analyticsProperty" in jsonified_request - assert jsonified_request["analyticsProperty"] == "analytics_property_value" +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.DeleteUserGroupRequest(), + {}, + ], +) +def test_delete_user_group(request_type, transport: str = "grpc"): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = marketingplatform_admin.SetPropertyServiceLevelResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = marketingplatform_admin.SetPropertyServiceLevelResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_user_group(request) - response = client.set_property_service_level(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.DeleteUserGroupRequest() + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the response is the type that we expect. + assert response is None -def test_set_property_service_level_rest_flattened(): +def test_delete_user_group_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = marketingplatform_admin.SetPropertyServiceLevelResponse() - - # get arguments that satisfy an http rule for this method - sample_request = { - "analytics_account_link": "organizations/sample1/analyticsAccountLinks/sample2" - } - - # get truthy value for each flattened field - mock_args = dict( - analytics_account_link="analytics_account_link_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = marketingplatform_admin.SetPropertyServiceLevelResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.set_property_service_level(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{analytics_account_link=organizations/*/analyticsAccountLinks/*}:setPropertyServiceLevel" - % client.transport._host, - args[1], - ) - - -def test_set_property_service_level_rest_flattened_error(transport: str = "rest"): - client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = marketingplatform_admin.DeleteUserGroupRequest( + name="name_value", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.set_property_service_level( - marketingplatform_admin.SetPropertyServiceLevelRequest(), - analytics_account_link="analytics_account_link_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_group), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_user_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.DeleteUserGroupRequest( + name="name_value", ) + assert args[0] == request_msg -def test_report_property_usage_rest_use_cached_wrapped_rpc(): +def test_delete_user_group_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -5244,702 +5685,11592 @@ def test_report_property_usage_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.report_property_usage - in client._transport._wrapped_methods - ) + assert client._transport.delete_user_group in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.report_property_usage] = ( + client._transport._wrapped_methods[client._transport.delete_user_group] = ( mock_rpc ) - request = {} - client.report_property_usage(request) + client.delete_user_group(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.report_property_usage(request) + client.delete_user_group(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_report_property_usage_rest_required_fields( - request_type=marketingplatform_admin.ReportPropertyUsageRequest, +@pytest.mark.asyncio +async def test_delete_user_group_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.MarketingplatformAdminServiceRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["organization"] = "" - request_init["month"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.delete_user_group + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseReportPropertyUsage, - "_BaseReportPropertyUsage__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_user_group + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.delete_user_group(request) - jsonified_request["organization"] = "organization_value" - jsonified_request["month"] = "month_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # verify required fields with non-default values are left alone - assert "organization" in jsonified_request - assert jsonified_request["organization"] == "organization_value" - assert "month" in jsonified_request - assert jsonified_request["month"] == "month_value" + await client.delete_user_group(request) - client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.DeleteUserGroupRequest(), + {}, + ], +) +async def test_delete_user_group_async(request_type, transport: str = "grpc_asyncio"): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = marketingplatform_admin.ReportPropertyUsageResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = marketingplatform_admin.ReportPropertyUsageResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_user_group(request) - response = client.report_property_usage(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.DeleteUserGroupRequest() + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the response is the type that we expect. + assert response is None -def test_report_property_usage_rest_flattened(): +def test_delete_user_group_field_headers(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = marketingplatform_admin.ReportPropertyUsageResponse() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.DeleteUserGroupRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"organization": "organizations/sample1"} + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - organization="organization_value", - ) - mock_args.update(sample_request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_group), "__call__" + ) as call: + call.return_value = None + client.delete_user_group(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = marketingplatform_admin.ReportPropertyUsageResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.report_property_usage(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_user_group_field_headers_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.DeleteUserGroupRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_group), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_user_group_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_user_group( + name="name_value", + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{organization=organizations/*}:reportPropertyUsage" - % client.transport._host, - args[1], - ) + 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_report_property_usage_rest_flattened_error(transport: str = "rest"): +def test_delete_user_group_flattened_error(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.report_property_usage( - marketingplatform_admin.ReportPropertyUsageRequest(), - organization="organization_value", + client.delete_user_group( + marketingplatform_admin.DeleteUserGroupRequest(), + name="name_value", ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.MarketingplatformAdminServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), +@pytest.mark.asyncio +async def test_delete_user_group_flattened_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - with pytest.raises(ValueError): - client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.MarketingplatformAdminServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = MarketingplatformAdminServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_user_group( + name="name_value", ) - # It is an error to provide an api_key and a transport instance. - transport = transports.MarketingplatformAdminServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_user_group_flattened_error_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = MarketingplatformAdminServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" + # Attempting to call a method with both a request object and flattened + # fields is an error. with pytest.raises(ValueError): - client = MarketingplatformAdminServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + await client.delete_user_group( + marketingplatform_admin.DeleteUserGroupRequest(), + name="name_value", ) - # It is an error to provide scopes and a transport instance. - transport = transports.MarketingplatformAdminServiceGrpcTransport( + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.GetUserGroupMemberRequest(), + {}, + ], +) +def test_get_user_group_member(request_type, transport: str = "grpc"): + client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - with pytest.raises(ValueError): - client = MarketingplatformAdminServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_group_member), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.UserGroupMember( + name="name_value", + membership_role=resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER, + user_email="user_email_value", ) + response = client.get_user_group_member(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.GetUserGroupMemberRequest() + assert args[0] == request -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.MarketingplatformAdminServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Establish that the response is the type that we expect. + assert isinstance(response, resources.UserGroupMember) + assert response.name == "name_value" + assert ( + response.membership_role + == resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER ) - client = MarketingplatformAdminServiceClient(transport=transport) - assert client.transport is transport -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.MarketingplatformAdminServiceGrpcTransport( +def test_get_user_group_member_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - channel = transport.grpc_channel - assert channel - transport = transports.MarketingplatformAdminServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = marketingplatform_admin.GetUserGroupMemberRequest( + name="name_value", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_group_member), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_user_group_member(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.GetUserGroupMemberRequest( + name="name_value", + ) + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_class", - [ - transports.MarketingplatformAdminServiceGrpcTransport, - transports.MarketingplatformAdminServiceGrpcAsyncIOTransport, - transports.MarketingplatformAdminServiceRestTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() +def test_get_user_group_member_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) -def test_transport_kind_grpc(): - transport = MarketingplatformAdminServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + # Ensure method has been cached + assert ( + client._transport.get_user_group_member + in client._transport._wrapped_methods + ) -def test_initialize_client_w_grpc(): - client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" - ) - assert client is not None + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_user_group_member] = ( + mock_rpc + ) + request = {} + client.get_user_group_member(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_organization_empty_call_grpc(): - client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + client.get_user_group_member(request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_organization), "__call__") as call: - call.return_value = resources.Organization() - client.get_organization(request=None) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.GetOrganizationRequest() - assert args[0] == request_msg +@pytest.mark.asyncio +async def test_get_user_group_member_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_organizations_empty_call_grpc(): - client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Ensure method has been cached + assert ( + client._client._transport.get_user_group_member + in client._client._transport._wrapped_methods + ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_organizations), "__call__" - ) as call: - call.return_value = marketingplatform_admin.ListOrganizationsResponse() - client.list_organizations(request=None) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_user_group_member + ] = mock_rpc - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.ListOrganizationsRequest() - assert args[0] == request_msg + request = {} + await client.get_user_group_member(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_find_sales_partner_managed_clients_empty_call_grpc(): - client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + await client.get_user_group_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.GetUserGroupMemberRequest(), + {}, + ], +) +async def test_get_user_group_member_async( + request_type, transport: str = "grpc_asyncio" +): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # Mock the actual call, and fake the request. + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.find_sales_partner_managed_clients), "__call__" + type(client.transport.get_user_group_member), "__call__" ) as call: - call.return_value = ( - marketingplatform_admin.FindSalesPartnerManagedClientsResponse() + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.UserGroupMember( + name="name_value", + membership_role=resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER, + ) ) - client.find_sales_partner_managed_clients(request=None) + response = await client.get_user_group_member(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.FindSalesPartnerManagedClientsRequest() - assert args[0] == request_msg + request = marketingplatform_admin.GetUserGroupMemberRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, resources.UserGroupMember) + assert response.name == "name_value" + assert ( + response.membership_role + == resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_analytics_account_links_empty_call_grpc(): + +def test_get_user_group_member_field_headers(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.GetUserGroupMemberRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_analytics_account_links), "__call__" + type(client.transport.get_user_group_member), "__call__" ) as call: - call.return_value = marketingplatform_admin.ListAnalyticsAccountLinksResponse() - client.list_analytics_account_links(request=None) + call.return_value = resources.UserGroupMember() + client.get_user_group_member(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.ListAnalyticsAccountLinksRequest() - assert args[0] == request_msg + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_analytics_account_link_empty_call_grpc(): - client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_get_user_group_member_field_headers_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.GetUserGroupMemberRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_analytics_account_link), "__call__" + type(client.transport.get_user_group_member), "__call__" ) as call: - call.return_value = resources.AnalyticsAccountLink() - client.create_analytics_account_link(request=None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.UserGroupMember() + ) + await client.get_user_group_member(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.CreateAnalyticsAccountLinkRequest() - assert args[0] == request_msg + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_analytics_account_link_empty_call_grpc(): +def test_get_user_group_member_flattened(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_analytics_account_link), "__call__" + type(client.transport.get_user_group_member), "__call__" ) as call: - call.return_value = None - client.delete_analytics_account_link(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.DeleteAnalyticsAccountLinkRequest() - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_set_property_service_level_empty_call_grpc(): - client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.set_property_service_level), "__call__" - ) as call: - call.return_value = marketingplatform_admin.SetPropertyServiceLevelResponse() - client.set_property_service_level(request=None) + # Designate an appropriate return value for the call. + call.return_value = resources.UserGroupMember() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_user_group_member( + name="name_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.SetPropertyServiceLevelRequest() - assert args[0] == request_msg + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_report_property_usage_empty_call_grpc(): +def test_get_user_group_member_flattened_error(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.report_property_usage), "__call__" - ) as call: - call.return_value = marketingplatform_admin.ReportPropertyUsageResponse() - client.report_property_usage(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.ReportPropertyUsageRequest() - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = MarketingplatformAdminServiceAsyncClient.get_transport_class( - "grpc_asyncio" - )(credentials=async_anonymous_credentials()) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = MarketingplatformAdminServiceAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" - ) - assert client is not None + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_user_group_member( + marketingplatform_admin.GetUserGroupMemberRequest(), + name="name_value", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_get_organization_empty_call_grpc_asyncio(): +async def test_get_user_group_member_flattened_async(): client = MarketingplatformAdminServiceAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_organization), "__call__") as call: + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_group_member), "__call__" + ) as call: # Designate an appropriate return value for the call. + call.return_value = resources.UserGroupMember() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.Organization( - name="name_value", - display_name="display_name_value", - ) + resources.UserGroupMember() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_user_group_member( + name="name_value", ) - await client.get_organization(request=None) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.GetOrganizationRequest() - assert args[0] == request_msg + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_list_organizations_empty_call_grpc_asyncio(): +async def test_get_user_group_member_flattened_error_async(): client = MarketingplatformAdminServiceAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_organizations), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - marketingplatform_admin.ListOrganizationsResponse( - next_page_token="next_page_token_value", - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_user_group_member( + marketingplatform_admin.GetUserGroupMemberRequest(), + name="name_value", ) - await client.list_organizations(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.ListOrganizationsRequest() - assert args[0] == request_msg -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_find_sales_partner_managed_clients_empty_call_grpc_asyncio(): - client = MarketingplatformAdminServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.ListUserGroupMembersRequest(), + {}, + ], +) +def test_list_user_group_members(request_type, transport: str = "grpc"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.find_sales_partner_managed_clients), "__call__" + type(client.transport.list_user_group_members), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - marketingplatform_admin.FindSalesPartnerManagedClientsResponse() + call.return_value = marketingplatform_admin.ListUserGroupMembersResponse( + next_page_token="next_page_token_value", ) - await client.find_sales_partner_managed_clients(request=None) + response = client.list_user_group_members(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.FindSalesPartnerManagedClientsRequest() - assert args[0] == request_msg + request = marketingplatform_admin.ListUserGroupMembersRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserGroupMembersPager) + assert response.next_page_token == "next_page_token_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_analytics_account_links_empty_call_grpc_asyncio(): - client = MarketingplatformAdminServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +def test_list_user_group_members_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # Mock the actual call, and fake the request. + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = marketingplatform_admin.ListUserGroupMembersRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_analytics_account_links), "__call__" + type(client.transport.list_user_group_members), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - marketingplatform_admin.ListAnalyticsAccountLinksResponse( - next_page_token="next_page_token_value", - ) + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - await client.list_analytics_account_links(request=None) - - # Establish that the underlying stub method was called. + client.list_user_group_members(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.ListAnalyticsAccountLinksRequest() + request_msg = marketingplatform_admin.ListUserGroupMembersRequest( + parent="parent_value", + page_token="page_token_value", + ) assert args[0] == request_msg -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_analytics_account_link_empty_call_grpc_asyncio(): - client = MarketingplatformAdminServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) +def test_list_user_group_members_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_analytics_account_link), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AnalyticsAccountLink( - name="name_value", - analytics_account="analytics_account_value", - display_name="display_name_value", - link_verification_state=resources.LinkVerificationState.LINK_VERIFICATION_STATE_VERIFIED, - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_user_group_members + in client._transport._wrapped_methods ) - await client.create_analytics_account_link(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.CreateAnalyticsAccountLinkRequest() - assert args[0] == request_msg + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_user_group_members + ] = mock_rpc + request = {} + client.list_user_group_members(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_analytics_account_link_empty_call_grpc_asyncio(): - client = MarketingplatformAdminServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + client.list_user_group_members(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_analytics_account_link), "__call__" + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_user_group_members_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_user_group_members + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_user_group_members + ] = mock_rpc + + request = {} + await client.list_user_group_members(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_user_group_members(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.ListUserGroupMembersRequest(), + {}, + ], +) +async def test_list_user_group_members_async( + request_type, transport: str = "grpc_asyncio" +): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_group_members), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_analytics_account_link(request=None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + marketingplatform_admin.ListUserGroupMembersResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_user_group_members(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.DeleteAnalyticsAccountLinkRequest() - assert args[0] == request_msg + request = marketingplatform_admin.ListUserGroupMembersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserGroupMembersAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_user_group_members_field_headers(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.ListUserGroupMembersRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_group_members), "__call__" + ) as call: + call.return_value = marketingplatform_admin.ListUserGroupMembersResponse() + client.list_user_group_members(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_user_group_members_field_headers_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.ListUserGroupMembersRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_group_members), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + marketingplatform_admin.ListUserGroupMembersResponse() + ) + await client.list_user_group_members(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_user_group_members_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_group_members), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = marketingplatform_admin.ListUserGroupMembersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_user_group_members( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_user_group_members_flattened_error(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_user_group_members( + marketingplatform_admin.ListUserGroupMembersRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_user_group_members_flattened_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_group_members), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = marketingplatform_admin.ListUserGroupMembersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + marketingplatform_admin.ListUserGroupMembersResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_user_group_members( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_user_group_members_flattened_error_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_user_group_members( + marketingplatform_admin.ListUserGroupMembersRequest(), + parent="parent_value", + ) + + +def test_list_user_group_members_pager(transport_name: str = "grpc"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_group_members), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[ + resources.UserGroupMember(), + resources.UserGroupMember(), + resources.UserGroupMember(), + ], + next_page_token="abc", + ), + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[], + next_page_token="def", + ), + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[ + resources.UserGroupMember(), + ], + next_page_token="ghi", + ), + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[ + resources.UserGroupMember(), + resources.UserGroupMember(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_user_group_members(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.UserGroupMember) for i in results) + + +def test_list_user_group_members_pages(transport_name: str = "grpc"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_group_members), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[ + resources.UserGroupMember(), + resources.UserGroupMember(), + resources.UserGroupMember(), + ], + next_page_token="abc", + ), + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[], + next_page_token="def", + ), + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[ + resources.UserGroupMember(), + ], + next_page_token="ghi", + ), + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[ + resources.UserGroupMember(), + resources.UserGroupMember(), + ], + ), + RuntimeError, + ) + pages = list(client.list_user_group_members(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_user_group_members_async_pager(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_group_members), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[ + resources.UserGroupMember(), + resources.UserGroupMember(), + resources.UserGroupMember(), + ], + next_page_token="abc", + ), + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[], + next_page_token="def", + ), + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[ + resources.UserGroupMember(), + ], + next_page_token="ghi", + ), + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[ + resources.UserGroupMember(), + resources.UserGroupMember(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_user_group_members( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.UserGroupMember) for i in responses) + + +@pytest.mark.asyncio +async def test_list_user_group_members_async_pages(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_group_members), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[ + resources.UserGroupMember(), + resources.UserGroupMember(), + resources.UserGroupMember(), + ], + next_page_token="abc", + ), + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[], + next_page_token="def", + ), + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[ + resources.UserGroupMember(), + ], + next_page_token="ghi", + ), + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[ + resources.UserGroupMember(), + resources.UserGroupMember(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_user_group_members(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", + [ + marketingplatform_admin.CreateUserGroupMemberRequest(), + {}, + ], +) +def test_create_user_group_member(request_type, transport: str = "grpc"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_group_member), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.UserGroupMember( + name="name_value", + membership_role=resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER, + user_email="user_email_value", + ) + response = client.create_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.CreateUserGroupMemberRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.UserGroupMember) + assert response.name == "name_value" + assert ( + response.membership_role + == resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER + ) + + +def test_create_user_group_member_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = marketingplatform_admin.CreateUserGroupMemberRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_group_member), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_user_group_member(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.CreateUserGroupMemberRequest( + parent="parent_value", + ) + assert args[0] == request_msg + + +def test_create_user_group_member_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_user_group_member + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_user_group_member + ] = mock_rpc + request = {} + client.create_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_user_group_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_user_group_member_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_user_group_member + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_user_group_member + ] = mock_rpc + + request = {} + await client.create_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_user_group_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.CreateUserGroupMemberRequest(), + {}, + ], +) +async def test_create_user_group_member_async( + request_type, transport: str = "grpc_asyncio" +): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_group_member), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.UserGroupMember( + name="name_value", + membership_role=resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER, + ) + ) + response = await client.create_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.CreateUserGroupMemberRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.UserGroupMember) + assert response.name == "name_value" + assert ( + response.membership_role + == resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER + ) + + +def test_create_user_group_member_field_headers(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.CreateUserGroupMemberRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_group_member), "__call__" + ) as call: + call.return_value = resources.UserGroupMember() + client.create_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_user_group_member_field_headers_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.CreateUserGroupMemberRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_group_member), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.UserGroupMember() + ) + await client.create_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_user_group_member_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_group_member), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.UserGroupMember() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_user_group_member( + parent="parent_value", + user_group_member=resources.UserGroupMember(user_email="user_email_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].user_group_member + mock_val = resources.UserGroupMember(user_email="user_email_value") + assert arg == mock_val + + +def test_create_user_group_member_flattened_error(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_user_group_member( + marketingplatform_admin.CreateUserGroupMemberRequest(), + parent="parent_value", + user_group_member=resources.UserGroupMember(user_email="user_email_value"), + ) + + +@pytest.mark.asyncio +async def test_create_user_group_member_flattened_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_group_member), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.UserGroupMember() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.UserGroupMember() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_user_group_member( + parent="parent_value", + user_group_member=resources.UserGroupMember(user_email="user_email_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].user_group_member + mock_val = resources.UserGroupMember(user_email="user_email_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_user_group_member_flattened_error_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_user_group_member( + marketingplatform_admin.CreateUserGroupMemberRequest(), + parent="parent_value", + user_group_member=resources.UserGroupMember(user_email="user_email_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.UpdateUserGroupMemberRequest(), + {}, + ], +) +def test_update_user_group_member(request_type, transport: str = "grpc"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_group_member), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.UserGroupMember( + name="name_value", + membership_role=resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER, + user_email="user_email_value", + ) + response = client.update_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.UpdateUserGroupMemberRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.UserGroupMember) + assert response.name == "name_value" + assert ( + response.membership_role + == resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER + ) + + +def test_update_user_group_member_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = marketingplatform_admin.UpdateUserGroupMemberRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_group_member), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_user_group_member(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.UpdateUserGroupMemberRequest() + assert args[0] == request_msg + + +def test_update_user_group_member_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_user_group_member + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_user_group_member + ] = mock_rpc + request = {} + client.update_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_user_group_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_user_group_member_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_user_group_member + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_user_group_member + ] = mock_rpc + + request = {} + await client.update_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_user_group_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.UpdateUserGroupMemberRequest(), + {}, + ], +) +async def test_update_user_group_member_async( + request_type, transport: str = "grpc_asyncio" +): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_group_member), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.UserGroupMember( + name="name_value", + membership_role=resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER, + ) + ) + response = await client.update_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.UpdateUserGroupMemberRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.UserGroupMember) + assert response.name == "name_value" + assert ( + response.membership_role + == resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER + ) + + +def test_update_user_group_member_field_headers(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.UpdateUserGroupMemberRequest() + + request.user_group_member.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_group_member), "__call__" + ) as call: + call.return_value = resources.UserGroupMember() + client.update_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "user_group_member.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_user_group_member_field_headers_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.UpdateUserGroupMemberRequest() + + request.user_group_member.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_group_member), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.UserGroupMember() + ) + await client.update_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "user_group_member.name=name_value", + ) in kw["metadata"] + + +def test_update_user_group_member_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_group_member), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.UserGroupMember() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_user_group_member( + user_group_member=resources.UserGroupMember(user_email="user_email_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].user_group_member + mock_val = resources.UserGroupMember(user_email="user_email_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_user_group_member_flattened_error(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_user_group_member( + marketingplatform_admin.UpdateUserGroupMemberRequest(), + user_group_member=resources.UserGroupMember(user_email="user_email_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_user_group_member_flattened_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_group_member), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.UserGroupMember() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.UserGroupMember() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_user_group_member( + user_group_member=resources.UserGroupMember(user_email="user_email_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].user_group_member + mock_val = resources.UserGroupMember(user_email="user_email_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_user_group_member_flattened_error_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_user_group_member( + marketingplatform_admin.UpdateUserGroupMemberRequest(), + user_group_member=resources.UserGroupMember(user_email="user_email_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.DeleteUserGroupMemberRequest(), + {}, + ], +) +def test_delete_user_group_member(request_type, transport: str = "grpc"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_group_member), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.DeleteUserGroupMemberRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_user_group_member_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = marketingplatform_admin.DeleteUserGroupMemberRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_group_member), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_user_group_member(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.DeleteUserGroupMemberRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_user_group_member_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_user_group_member + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_user_group_member + ] = mock_rpc + request = {} + client.delete_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_user_group_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_user_group_member_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_user_group_member + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_user_group_member + ] = mock_rpc + + request = {} + await client.delete_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_user_group_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.DeleteUserGroupMemberRequest(), + {}, + ], +) +async def test_delete_user_group_member_async( + request_type, transport: str = "grpc_asyncio" +): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_group_member), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.DeleteUserGroupMemberRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_user_group_member_field_headers(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.DeleteUserGroupMemberRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_group_member), "__call__" + ) as call: + call.return_value = None + client.delete_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_user_group_member_field_headers_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.DeleteUserGroupMemberRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_group_member), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_user_group_member_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_group_member), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_user_group_member( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_user_group_member_flattened_error(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_user_group_member( + marketingplatform_admin.DeleteUserGroupMemberRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_user_group_member_flattened_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_group_member), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_user_group_member( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_user_group_member_flattened_error_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_user_group_member( + marketingplatform_admin.DeleteUserGroupMemberRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.GetAdminAccessBindingRequest(), + {}, + ], +) +def test_get_admin_access_binding(request_type, transport: str = "grpc"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_admin_access_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AdminAccessBinding( + name="name_value", + organization_roles=[resources.OrganizationRole.ORG_ADMIN_ROLE], + user_email="user_email_value", + ) + response = client.get_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.GetAdminAccessBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AdminAccessBinding) + assert response.name == "name_value" + assert response.organization_roles == [resources.OrganizationRole.ORG_ADMIN_ROLE] + + +def test_get_admin_access_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = marketingplatform_admin.GetAdminAccessBindingRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_admin_access_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_admin_access_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.GetAdminAccessBindingRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_admin_access_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_admin_access_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_admin_access_binding + ] = mock_rpc + request = {} + client.get_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_admin_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_admin_access_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_admin_access_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_admin_access_binding + ] = mock_rpc + + request = {} + await client.get_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_admin_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.GetAdminAccessBindingRequest(), + {}, + ], +) +async def test_get_admin_access_binding_async( + request_type, transport: str = "grpc_asyncio" +): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_admin_access_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AdminAccessBinding( + name="name_value", + organization_roles=[resources.OrganizationRole.ORG_ADMIN_ROLE], + ) + ) + response = await client.get_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.GetAdminAccessBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AdminAccessBinding) + assert response.name == "name_value" + assert response.organization_roles == [resources.OrganizationRole.ORG_ADMIN_ROLE] + + +def test_get_admin_access_binding_field_headers(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.GetAdminAccessBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_admin_access_binding), "__call__" + ) as call: + call.return_value = resources.AdminAccessBinding() + client.get_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_admin_access_binding_field_headers_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.GetAdminAccessBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_admin_access_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AdminAccessBinding() + ) + await client.get_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_admin_access_binding_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_admin_access_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AdminAccessBinding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_admin_access_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_admin_access_binding_flattened_error(): + client = MarketingplatformAdminServiceClient( + credentials=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_admin_access_binding( + marketingplatform_admin.GetAdminAccessBindingRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_admin_access_binding_flattened_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_admin_access_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AdminAccessBinding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AdminAccessBinding() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_admin_access_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_admin_access_binding_flattened_error_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_admin_access_binding( + marketingplatform_admin.GetAdminAccessBindingRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.ListAdminAccessBindingsRequest(), + {}, + ], +) +def test_list_admin_access_bindings(request_type, transport: str = "grpc"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_admin_access_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = marketingplatform_admin.ListAdminAccessBindingsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_admin_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.ListAdminAccessBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAdminAccessBindingsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_admin_access_bindings_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = marketingplatform_admin.ListAdminAccessBindingsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_admin_access_bindings), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_admin_access_bindings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.ListAdminAccessBindingsRequest( + parent="parent_value", + page_token="page_token_value", + ) + assert args[0] == request_msg + + +def test_list_admin_access_bindings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_admin_access_bindings + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_admin_access_bindings + ] = mock_rpc + request = {} + client.list_admin_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_admin_access_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_admin_access_bindings_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_admin_access_bindings + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_admin_access_bindings + ] = mock_rpc + + request = {} + await client.list_admin_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_admin_access_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.ListAdminAccessBindingsRequest(), + {}, + ], +) +async def test_list_admin_access_bindings_async( + request_type, transport: str = "grpc_asyncio" +): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_admin_access_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + marketingplatform_admin.ListAdminAccessBindingsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_admin_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.ListAdminAccessBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAdminAccessBindingsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_admin_access_bindings_field_headers(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.ListAdminAccessBindingsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_admin_access_bindings), "__call__" + ) as call: + call.return_value = marketingplatform_admin.ListAdminAccessBindingsResponse() + client.list_admin_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_admin_access_bindings_field_headers_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.ListAdminAccessBindingsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_admin_access_bindings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + marketingplatform_admin.ListAdminAccessBindingsResponse() + ) + await client.list_admin_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_admin_access_bindings_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_admin_access_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = marketingplatform_admin.ListAdminAccessBindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_admin_access_bindings( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_admin_access_bindings_flattened_error(): + client = MarketingplatformAdminServiceClient( + credentials=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_admin_access_bindings( + marketingplatform_admin.ListAdminAccessBindingsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_admin_access_bindings_flattened_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_admin_access_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = marketingplatform_admin.ListAdminAccessBindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + marketingplatform_admin.ListAdminAccessBindingsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_admin_access_bindings( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_admin_access_bindings_flattened_error_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_admin_access_bindings( + marketingplatform_admin.ListAdminAccessBindingsRequest(), + parent="parent_value", + ) + + +def test_list_admin_access_bindings_pager(transport_name: str = "grpc"): + client = MarketingplatformAdminServiceClient( + 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_admin_access_bindings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[ + resources.AdminAccessBinding(), + resources.AdminAccessBinding(), + resources.AdminAccessBinding(), + ], + next_page_token="abc", + ), + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[], + next_page_token="def", + ), + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[ + resources.AdminAccessBinding(), + ], + next_page_token="ghi", + ), + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[ + resources.AdminAccessBinding(), + resources.AdminAccessBinding(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_admin_access_bindings( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.AdminAccessBinding) for i in results) + + +def test_list_admin_access_bindings_pages(transport_name: str = "grpc"): + client = MarketingplatformAdminServiceClient( + 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_admin_access_bindings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[ + resources.AdminAccessBinding(), + resources.AdminAccessBinding(), + resources.AdminAccessBinding(), + ], + next_page_token="abc", + ), + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[], + next_page_token="def", + ), + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[ + resources.AdminAccessBinding(), + ], + next_page_token="ghi", + ), + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[ + resources.AdminAccessBinding(), + resources.AdminAccessBinding(), + ], + ), + RuntimeError, + ) + pages = list(client.list_admin_access_bindings(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_admin_access_bindings_async_pager(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_admin_access_bindings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[ + resources.AdminAccessBinding(), + resources.AdminAccessBinding(), + resources.AdminAccessBinding(), + ], + next_page_token="abc", + ), + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[], + next_page_token="def", + ), + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[ + resources.AdminAccessBinding(), + ], + next_page_token="ghi", + ), + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[ + resources.AdminAccessBinding(), + resources.AdminAccessBinding(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_admin_access_bindings( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.AdminAccessBinding) for i in responses) + + +@pytest.mark.asyncio +async def test_list_admin_access_bindings_async_pages(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_admin_access_bindings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[ + resources.AdminAccessBinding(), + resources.AdminAccessBinding(), + resources.AdminAccessBinding(), + ], + next_page_token="abc", + ), + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[], + next_page_token="def", + ), + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[ + resources.AdminAccessBinding(), + ], + next_page_token="ghi", + ), + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[ + resources.AdminAccessBinding(), + resources.AdminAccessBinding(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_admin_access_bindings(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", + [ + marketingplatform_admin.CreateAdminAccessBindingRequest(), + {}, + ], +) +def test_create_admin_access_binding(request_type, transport: str = "grpc"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_admin_access_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AdminAccessBinding( + name="name_value", + organization_roles=[resources.OrganizationRole.ORG_ADMIN_ROLE], + user_email="user_email_value", + ) + response = client.create_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.CreateAdminAccessBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AdminAccessBinding) + assert response.name == "name_value" + assert response.organization_roles == [resources.OrganizationRole.ORG_ADMIN_ROLE] + + +def test_create_admin_access_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = marketingplatform_admin.CreateAdminAccessBindingRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_admin_access_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_admin_access_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.CreateAdminAccessBindingRequest( + parent="parent_value", + ) + assert args[0] == request_msg + + +def test_create_admin_access_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_admin_access_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_admin_access_binding + ] = mock_rpc + request = {} + client.create_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_admin_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_admin_access_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_admin_access_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_admin_access_binding + ] = mock_rpc + + request = {} + await client.create_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_admin_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.CreateAdminAccessBindingRequest(), + {}, + ], +) +async def test_create_admin_access_binding_async( + request_type, transport: str = "grpc_asyncio" +): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_admin_access_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AdminAccessBinding( + name="name_value", + organization_roles=[resources.OrganizationRole.ORG_ADMIN_ROLE], + ) + ) + response = await client.create_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.CreateAdminAccessBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AdminAccessBinding) + assert response.name == "name_value" + assert response.organization_roles == [resources.OrganizationRole.ORG_ADMIN_ROLE] + + +def test_create_admin_access_binding_field_headers(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.CreateAdminAccessBindingRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_admin_access_binding), "__call__" + ) as call: + call.return_value = resources.AdminAccessBinding() + client.create_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_admin_access_binding_field_headers_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.CreateAdminAccessBindingRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_admin_access_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AdminAccessBinding() + ) + await client.create_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_admin_access_binding_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_admin_access_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AdminAccessBinding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_admin_access_binding( + parent="parent_value", + admin_access_binding=resources.AdminAccessBinding( + user_email="user_email_value" + ), + ) + + # Establish that the 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].admin_access_binding + mock_val = resources.AdminAccessBinding(user_email="user_email_value") + assert arg == mock_val + + +def test_create_admin_access_binding_flattened_error(): + client = MarketingplatformAdminServiceClient( + credentials=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_admin_access_binding( + marketingplatform_admin.CreateAdminAccessBindingRequest(), + parent="parent_value", + admin_access_binding=resources.AdminAccessBinding( + user_email="user_email_value" + ), + ) + + +@pytest.mark.asyncio +async def test_create_admin_access_binding_flattened_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_admin_access_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AdminAccessBinding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AdminAccessBinding() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_admin_access_binding( + parent="parent_value", + admin_access_binding=resources.AdminAccessBinding( + user_email="user_email_value" + ), + ) + + # Establish that 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].admin_access_binding + mock_val = resources.AdminAccessBinding(user_email="user_email_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_admin_access_binding_flattened_error_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_admin_access_binding( + marketingplatform_admin.CreateAdminAccessBindingRequest(), + parent="parent_value", + admin_access_binding=resources.AdminAccessBinding( + user_email="user_email_value" + ), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.UpdateAdminAccessBindingRequest(), + {}, + ], +) +def test_update_admin_access_binding(request_type, transport: str = "grpc"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_admin_access_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AdminAccessBinding( + name="name_value", + organization_roles=[resources.OrganizationRole.ORG_ADMIN_ROLE], + user_email="user_email_value", + ) + response = client.update_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.UpdateAdminAccessBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AdminAccessBinding) + assert response.name == "name_value" + assert response.organization_roles == [resources.OrganizationRole.ORG_ADMIN_ROLE] + + +def test_update_admin_access_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = marketingplatform_admin.UpdateAdminAccessBindingRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_admin_access_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_admin_access_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.UpdateAdminAccessBindingRequest() + assert args[0] == request_msg + + +def test_update_admin_access_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_admin_access_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_admin_access_binding + ] = mock_rpc + request = {} + client.update_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_admin_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_admin_access_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_admin_access_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_admin_access_binding + ] = mock_rpc + + request = {} + await client.update_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_admin_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.UpdateAdminAccessBindingRequest(), + {}, + ], +) +async def test_update_admin_access_binding_async( + request_type, transport: str = "grpc_asyncio" +): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_admin_access_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AdminAccessBinding( + name="name_value", + organization_roles=[resources.OrganizationRole.ORG_ADMIN_ROLE], + ) + ) + response = await client.update_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = marketingplatform_admin.UpdateAdminAccessBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AdminAccessBinding) + assert response.name == "name_value" + assert response.organization_roles == [resources.OrganizationRole.ORG_ADMIN_ROLE] + + +def test_update_admin_access_binding_field_headers(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.UpdateAdminAccessBindingRequest() + + request.admin_access_binding.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_admin_access_binding), "__call__" + ) as call: + call.return_value = resources.AdminAccessBinding() + client.update_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "admin_access_binding.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_admin_access_binding_field_headers_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = marketingplatform_admin.UpdateAdminAccessBindingRequest() + + request.admin_access_binding.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_admin_access_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AdminAccessBinding() + ) + await client.update_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "admin_access_binding.name=name_value", + ) in kw["metadata"] + + +def test_update_admin_access_binding_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_admin_access_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AdminAccessBinding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_admin_access_binding( + admin_access_binding=resources.AdminAccessBinding( + user_email="user_email_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].admin_access_binding + mock_val = resources.AdminAccessBinding(user_email="user_email_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_admin_access_binding_flattened_error(): + client = MarketingplatformAdminServiceClient( + credentials=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_admin_access_binding( + marketingplatform_admin.UpdateAdminAccessBindingRequest(), + admin_access_binding=resources.AdminAccessBinding( + user_email="user_email_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_admin_access_binding_flattened_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_admin_access_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AdminAccessBinding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AdminAccessBinding() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_admin_access_binding( + admin_access_binding=resources.AdminAccessBinding( + user_email="user_email_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].admin_access_binding + mock_val = resources.AdminAccessBinding(user_email="user_email_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_admin_access_binding_flattened_error_async(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_admin_access_binding( + marketingplatform_admin.UpdateAdminAccessBindingRequest(), + admin_access_binding=resources.AdminAccessBinding( + user_email="user_email_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_get_organization_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_organization in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_organization] = ( + mock_rpc + ) + + request = {} + client.get_organization(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_organization(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_organization_rest_required_fields( + request_type=marketingplatform_admin.GetOrganizationRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetOrganization, + "_BaseGetOrganization__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Organization() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.Organization.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_organization(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_organization_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Organization() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.Organization.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_organization(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=organizations/*}" % client.transport._host, args[1] + ) + + +def test_get_organization_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_organization( + marketingplatform_admin.GetOrganizationRequest(), + name="name_value", + ) + + +def test_list_organizations_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_organizations in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_organizations] = ( + mock_rpc + ) + + request = {} + client.list_organizations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_organizations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_organizations_rest_pager(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + 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 = ( + marketingplatform_admin.ListOrganizationsResponse( + organizations=[ + resources.Organization(), + resources.Organization(), + resources.Organization(), + ], + next_page_token="abc", + ), + marketingplatform_admin.ListOrganizationsResponse( + organizations=[], + next_page_token="def", + ), + marketingplatform_admin.ListOrganizationsResponse( + organizations=[ + resources.Organization(), + ], + next_page_token="ghi", + ), + marketingplatform_admin.ListOrganizationsResponse( + organizations=[ + resources.Organization(), + resources.Organization(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + marketingplatform_admin.ListOrganizationsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {} + + pager = client.list_organizations(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Organization) for i in results) + + pages = list(client.list_organizations(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_find_sales_partner_managed_clients_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.find_sales_partner_managed_clients + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.find_sales_partner_managed_clients + ] = mock_rpc + + request = {} + client.find_sales_partner_managed_clients(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.find_sales_partner_managed_clients(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_find_sales_partner_managed_clients_rest_required_fields( + request_type=marketingplatform_admin.FindSalesPartnerManagedClientsRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request_init["organization"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseFindSalesPartnerManagedClients, + "_BaseFindSalesPartnerManagedClients__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["organization"] = "organization_value" + + # verify required fields with non-default values are left alone + assert "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = marketingplatform_admin.FindSalesPartnerManagedClientsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + marketingplatform_admin.FindSalesPartnerManagedClientsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.find_sales_partner_managed_clients(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_analytics_account_links_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_analytics_account_links + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_analytics_account_links + ] = mock_rpc + + request = {} + client.list_analytics_account_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_analytics_account_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_analytics_account_links_rest_required_fields( + request_type=marketingplatform_admin.ListAnalyticsAccountLinksRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListAnalyticsAccountLinks, + "_BaseListAnalyticsAccountLinks__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = marketingplatform_admin.ListAnalyticsAccountLinksResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = marketingplatform_admin.ListAnalyticsAccountLinksResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_analytics_account_links(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_analytics_account_links_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = marketingplatform_admin.ListAnalyticsAccountLinksResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = marketingplatform_admin.ListAnalyticsAccountLinksResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_analytics_account_links(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=organizations/*}/analyticsAccountLinks" + % client.transport._host, + args[1], + ) + + +def test_list_analytics_account_links_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.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_analytics_account_links( + marketingplatform_admin.ListAnalyticsAccountLinksRequest(), + parent="parent_value", + ) + + +def test_list_analytics_account_links_rest_pager(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + 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 = ( + marketingplatform_admin.ListAnalyticsAccountLinksResponse( + analytics_account_links=[ + resources.AnalyticsAccountLink(), + resources.AnalyticsAccountLink(), + resources.AnalyticsAccountLink(), + ], + next_page_token="abc", + ), + marketingplatform_admin.ListAnalyticsAccountLinksResponse( + analytics_account_links=[], + next_page_token="def", + ), + marketingplatform_admin.ListAnalyticsAccountLinksResponse( + analytics_account_links=[ + resources.AnalyticsAccountLink(), + ], + next_page_token="ghi", + ), + marketingplatform_admin.ListAnalyticsAccountLinksResponse( + analytics_account_links=[ + resources.AnalyticsAccountLink(), + resources.AnalyticsAccountLink(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + marketingplatform_admin.ListAnalyticsAccountLinksResponse.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": "organizations/sample1"} + + pager = client.list_analytics_account_links(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.AnalyticsAccountLink) for i in results) + + pages = list(client.list_analytics_account_links(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_analytics_account_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_analytics_account_link + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_analytics_account_link + ] = mock_rpc + + request = {} + client.create_analytics_account_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_analytics_account_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_analytics_account_link_rest_required_fields( + request_type=marketingplatform_admin.CreateAnalyticsAccountLinkRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseCreateAnalyticsAccountLink, + "_BaseCreateAnalyticsAccountLink__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.AnalyticsAccountLink() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.AnalyticsAccountLink.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_analytics_account_link(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_analytics_account_link_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.AnalyticsAccountLink() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + analytics_account_link=resources.AnalyticsAccountLink(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.AnalyticsAccountLink.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_analytics_account_link(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=organizations/*}/analyticsAccountLinks" + % client.transport._host, + args[1], + ) + + +def test_create_analytics_account_link_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.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_analytics_account_link( + marketingplatform_admin.CreateAnalyticsAccountLinkRequest(), + parent="parent_value", + analytics_account_link=resources.AnalyticsAccountLink(name="name_value"), + ) + + +def test_delete_analytics_account_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_analytics_account_link + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_analytics_account_link + ] = mock_rpc + + request = {} + client.delete_analytics_account_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_analytics_account_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_analytics_account_link_rest_required_fields( + request_type=marketingplatform_admin.DeleteAnalyticsAccountLinkRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseDeleteAnalyticsAccountLink, + "_BaseDeleteAnalyticsAccountLink__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_analytics_account_link(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_analytics_account_link_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/analyticsAccountLinks/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_analytics_account_link(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=organizations/*/analyticsAccountLinks/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_analytics_account_link_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.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_analytics_account_link( + marketingplatform_admin.DeleteAnalyticsAccountLinkRequest(), + name="name_value", + ) + + +def test_set_property_service_level_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.set_property_service_level + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.set_property_service_level + ] = mock_rpc + + request = {} + client.set_property_service_level(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_property_service_level(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_set_property_service_level_rest_required_fields( + request_type=marketingplatform_admin.SetPropertyServiceLevelRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request_init["analytics_account_link"] = "" + request_init["analytics_property"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseSetPropertyServiceLevel, + "_BaseSetPropertyServiceLevel__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["analyticsAccountLink"] = "analytics_account_link_value" + jsonified_request["analyticsProperty"] = "analytics_property_value" + + # verify required fields with non-default values are left alone + assert "analyticsAccountLink" in jsonified_request + assert jsonified_request["analyticsAccountLink"] == "analytics_account_link_value" + assert "analyticsProperty" in jsonified_request + assert jsonified_request["analyticsProperty"] == "analytics_property_value" + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = marketingplatform_admin.SetPropertyServiceLevelResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = marketingplatform_admin.SetPropertyServiceLevelResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_property_service_level(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_set_property_service_level_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = marketingplatform_admin.SetPropertyServiceLevelResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "analytics_account_link": "organizations/sample1/analyticsAccountLinks/sample2" + } + + # get truthy value for each flattened field + mock_args = dict( + analytics_account_link="analytics_account_link_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = marketingplatform_admin.SetPropertyServiceLevelResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.set_property_service_level(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{analytics_account_link=organizations/*/analyticsAccountLinks/*}:setPropertyServiceLevel" + % client.transport._host, + args[1], + ) + + +def test_set_property_service_level_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_property_service_level( + marketingplatform_admin.SetPropertyServiceLevelRequest(), + analytics_account_link="analytics_account_link_value", + ) + + +def test_report_property_usage_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.report_property_usage + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.report_property_usage] = ( + mock_rpc + ) + + request = {} + client.report_property_usage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.report_property_usage(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_report_property_usage_rest_required_fields( + request_type=marketingplatform_admin.ReportPropertyUsageRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request_init["organization"] = "" + request_init["month"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseReportPropertyUsage, + "_BaseReportPropertyUsage__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["organization"] = "organization_value" + jsonified_request["month"] = "month_value" + + # verify required fields with non-default values are left alone + assert "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + assert "month" in jsonified_request + assert jsonified_request["month"] == "month_value" + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = marketingplatform_admin.ReportPropertyUsageResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = marketingplatform_admin.ReportPropertyUsageResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.report_property_usage(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_report_property_usage_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = marketingplatform_admin.ReportPropertyUsageResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"organization": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + organization="organization_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = marketingplatform_admin.ReportPropertyUsageResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.report_property_usage(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{organization=organizations/*}:reportPropertyUsage" + % client.transport._host, + args[1], + ) + + +def test_report_property_usage_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.report_property_usage( + marketingplatform_admin.ReportPropertyUsageRequest(), + organization="organization_value", + ) + + +def test_get_user_group_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_user_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_user_group] = mock_rpc + + request = {} + client.get_user_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_user_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_user_group_rest_required_fields( + request_type=marketingplatform_admin.GetUserGroupRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetUserGroup, + "_BaseGetUserGroup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.UserGroup() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.UserGroup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_user_group(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_user_group_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.UserGroup() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/userGroups/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.UserGroup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_user_group(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=organizations/*/userGroups/*}" % client.transport._host, + args[1], + ) + + +def test_get_user_group_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_user_group( + marketingplatform_admin.GetUserGroupRequest(), + name="name_value", + ) + + +def test_list_user_groups_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_user_groups in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_user_groups] = ( + mock_rpc + ) + + request = {} + client.list_user_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_user_groups(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_user_groups_rest_required_fields( + request_type=marketingplatform_admin.ListUserGroupsRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListUserGroups, + "_BaseListUserGroups__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = marketingplatform_admin.ListUserGroupsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = marketingplatform_admin.ListUserGroupsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_user_groups(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_user_groups_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = marketingplatform_admin.ListUserGroupsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = marketingplatform_admin.ListUserGroupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_user_groups(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=organizations/*}/userGroups" % client.transport._host, + args[1], + ) + + +def test_list_user_groups_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_user_groups( + marketingplatform_admin.ListUserGroupsRequest(), + parent="parent_value", + ) + + +def test_list_user_groups_rest_pager(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + 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 = ( + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[ + resources.UserGroup(), + resources.UserGroup(), + resources.UserGroup(), + ], + next_page_token="abc", + ), + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[], + next_page_token="def", + ), + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[ + resources.UserGroup(), + ], + next_page_token="ghi", + ), + marketingplatform_admin.ListUserGroupsResponse( + user_groups=[ + resources.UserGroup(), + resources.UserGroup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + marketingplatform_admin.ListUserGroupsResponse.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": "organizations/sample1"} + + pager = client.list_user_groups(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.UserGroup) for i in results) + + pages = list(client.list_user_groups(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_user_group_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_user_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_user_group] = ( + mock_rpc + ) + + request = {} + client.create_user_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_user_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_user_group_rest_required_fields( + request_type=marketingplatform_admin.CreateUserGroupRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseCreateUserGroup, + "_BaseCreateUserGroup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.UserGroup() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.UserGroup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_user_group(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_user_group_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.UserGroup() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + user_group=resources.UserGroup(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.UserGroup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_user_group(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=organizations/*}/userGroups" % client.transport._host, + args[1], + ) + + +def test_create_user_group_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_user_group( + marketingplatform_admin.CreateUserGroupRequest(), + parent="parent_value", + user_group=resources.UserGroup(name="name_value"), + ) + + +def test_update_user_group_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_user_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_user_group] = ( + mock_rpc + ) + + request = {} + client.update_user_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_user_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_user_group_rest_required_fields( + request_type=marketingplatform_admin.UpdateUserGroupRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateUserGroup, + "_BaseUpdateUserGroup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("updateMask",)) + + # verify required fields with non-default values are left alone + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.UserGroup() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.UserGroup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_user_group(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_user_group_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.UserGroup() + + # get arguments that satisfy an http rule for this method + sample_request = { + "user_group": {"name": "organizations/sample1/userGroups/sample2"} + } + + # get truthy value for each flattened field + mock_args = dict( + user_group=resources.UserGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.UserGroup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_user_group(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{user_group.name=organizations/*/userGroups/*}" + % client.transport._host, + args[1], + ) + + +def test_update_user_group_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_user_group( + marketingplatform_admin.UpdateUserGroupRequest(), + user_group=resources.UserGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_user_group_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_user_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_user_group] = ( + mock_rpc + ) + + request = {} + client.delete_user_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_user_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_user_group_rest_required_fields( + request_type=marketingplatform_admin.DeleteUserGroupRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseDeleteUserGroup, + "_BaseDeleteUserGroup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_user_group(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_user_group_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/userGroups/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_user_group(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=organizations/*/userGroups/*}" % client.transport._host, + args[1], + ) + + +def test_delete_user_group_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_user_group( + marketingplatform_admin.DeleteUserGroupRequest(), + name="name_value", + ) + + +def test_get_user_group_member_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_user_group_member + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_user_group_member] = ( + mock_rpc + ) + + request = {} + client.get_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_user_group_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_user_group_member_rest_required_fields( + request_type=marketingplatform_admin.GetUserGroupMemberRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetUserGroupMember, + "_BaseGetUserGroupMember__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.UserGroupMember() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.UserGroupMember.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_user_group_member(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_user_group_member_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.UserGroupMember() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/userGroups/sample2/members/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.UserGroupMember.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_user_group_member(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=organizations/*/userGroups/*/members/*}" + % client.transport._host, + args[1], + ) + + +def test_get_user_group_member_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_user_group_member( + marketingplatform_admin.GetUserGroupMemberRequest(), + name="name_value", + ) + + +def test_list_user_group_members_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_user_group_members + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_user_group_members + ] = mock_rpc + + request = {} + client.list_user_group_members(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_user_group_members(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_user_group_members_rest_required_fields( + request_type=marketingplatform_admin.ListUserGroupMembersRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListUserGroupMembers, + "_BaseListUserGroupMembers__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = marketingplatform_admin.ListUserGroupMembersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = marketingplatform_admin.ListUserGroupMembersResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_user_group_members(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_user_group_members_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = marketingplatform_admin.ListUserGroupMembersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1/userGroups/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = marketingplatform_admin.ListUserGroupMembersResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_user_group_members(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=organizations/*/userGroups/*}/members" + % client.transport._host, + args[1], + ) + + +def test_list_user_group_members_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_user_group_members( + marketingplatform_admin.ListUserGroupMembersRequest(), + parent="parent_value", + ) + + +def test_list_user_group_members_rest_pager(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + 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 = ( + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[ + resources.UserGroupMember(), + resources.UserGroupMember(), + resources.UserGroupMember(), + ], + next_page_token="abc", + ), + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[], + next_page_token="def", + ), + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[ + resources.UserGroupMember(), + ], + next_page_token="ghi", + ), + marketingplatform_admin.ListUserGroupMembersResponse( + user_group_members=[ + resources.UserGroupMember(), + resources.UserGroupMember(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + marketingplatform_admin.ListUserGroupMembersResponse.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": "organizations/sample1/userGroups/sample2"} + + pager = client.list_user_group_members(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.UserGroupMember) for i in results) + + pages = list(client.list_user_group_members(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_user_group_member_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_user_group_member + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_user_group_member + ] = mock_rpc + + request = {} + client.create_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_user_group_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_user_group_member_rest_required_fields( + request_type=marketingplatform_admin.CreateUserGroupMemberRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseCreateUserGroupMember, + "_BaseCreateUserGroupMember__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.UserGroupMember() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.UserGroupMember.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_user_group_member(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_user_group_member_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.UserGroupMember() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1/userGroups/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + user_group_member=resources.UserGroupMember(user_email="user_email_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.UserGroupMember.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_user_group_member(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=organizations/*/userGroups/*}/members" + % client.transport._host, + args[1], + ) + + +def test_create_user_group_member_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_user_group_member( + marketingplatform_admin.CreateUserGroupMemberRequest(), + parent="parent_value", + user_group_member=resources.UserGroupMember(user_email="user_email_value"), + ) + + +def test_update_user_group_member_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_user_group_member + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_user_group_member + ] = mock_rpc + + request = {} + client.update_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_user_group_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_user_group_member_rest_required_fields( + request_type=marketingplatform_admin.UpdateUserGroupMemberRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateUserGroupMember, + "_BaseUpdateUserGroupMember__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("updateMask",)) + + # verify required fields with non-default values are left alone + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.UserGroupMember() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.UserGroupMember.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_user_group_member(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_user_group_member_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.UserGroupMember() + + # get arguments that satisfy an http rule for this method + sample_request = { + "user_group_member": { + "name": "organizations/sample1/userGroups/sample2/members/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + user_group_member=resources.UserGroupMember(user_email="user_email_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.UserGroupMember.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_user_group_member(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{user_group_member.name=organizations/*/userGroups/*/members/*}" + % client.transport._host, + args[1], + ) + + +def test_update_user_group_member_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_user_group_member( + marketingplatform_admin.UpdateUserGroupMemberRequest(), + user_group_member=resources.UserGroupMember(user_email="user_email_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_user_group_member_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_user_group_member + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_user_group_member + ] = mock_rpc + + request = {} + client.delete_user_group_member(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_user_group_member(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_user_group_member_rest_required_fields( + request_type=marketingplatform_admin.DeleteUserGroupMemberRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseDeleteUserGroupMember, + "_BaseDeleteUserGroupMember__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_user_group_member(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_user_group_member_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/userGroups/sample2/members/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 = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_user_group_member(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=organizations/*/userGroups/*/members/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_user_group_member_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_user_group_member( + marketingplatform_admin.DeleteUserGroupMemberRequest(), + name="name_value", + ) + + +def test_get_admin_access_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_admin_access_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_admin_access_binding + ] = mock_rpc + + request = {} + client.get_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_admin_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_admin_access_binding_rest_required_fields( + request_type=marketingplatform_admin.GetAdminAccessBindingRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetAdminAccessBinding, + "_BaseGetAdminAccessBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.AdminAccessBinding() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.AdminAccessBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_admin_access_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_admin_access_binding_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.AdminAccessBinding() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/adminAccessBindings/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.AdminAccessBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_admin_access_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=organizations/*/adminAccessBindings/*}" + % client.transport._host, + args[1], + ) + + +def test_get_admin_access_binding_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.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_admin_access_binding( + marketingplatform_admin.GetAdminAccessBindingRequest(), + name="name_value", + ) + + +def test_list_admin_access_bindings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_admin_access_bindings + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_admin_access_bindings + ] = mock_rpc + + request = {} + client.list_admin_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_admin_access_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_admin_access_bindings_rest_required_fields( + request_type=marketingplatform_admin.ListAdminAccessBindingsRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListAdminAccessBindings, + "_BaseListAdminAccessBindings__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = marketingplatform_admin.ListAdminAccessBindingsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = marketingplatform_admin.ListAdminAccessBindingsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_admin_access_bindings(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_admin_access_bindings_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = marketingplatform_admin.ListAdminAccessBindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = marketingplatform_admin.ListAdminAccessBindingsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_admin_access_bindings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=organizations/*}/adminAccessBindings" + % client.transport._host, + args[1], + ) + + +def test_list_admin_access_bindings_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.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_admin_access_bindings( + marketingplatform_admin.ListAdminAccessBindingsRequest(), + parent="parent_value", + ) + + +def test_list_admin_access_bindings_rest_pager(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + 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 = ( + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[ + resources.AdminAccessBinding(), + resources.AdminAccessBinding(), + resources.AdminAccessBinding(), + ], + next_page_token="abc", + ), + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[], + next_page_token="def", + ), + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[ + resources.AdminAccessBinding(), + ], + next_page_token="ghi", + ), + marketingplatform_admin.ListAdminAccessBindingsResponse( + admin_access_bindings=[ + resources.AdminAccessBinding(), + resources.AdminAccessBinding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + marketingplatform_admin.ListAdminAccessBindingsResponse.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": "organizations/sample1"} + + pager = client.list_admin_access_bindings(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.AdminAccessBinding) for i in results) + + pages = list(client.list_admin_access_bindings(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_admin_access_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_admin_access_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_admin_access_binding + ] = mock_rpc + + request = {} + client.create_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_admin_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_admin_access_binding_rest_required_fields( + request_type=marketingplatform_admin.CreateAdminAccessBindingRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseCreateAdminAccessBinding, + "_BaseCreateAdminAccessBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.AdminAccessBinding() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.AdminAccessBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_admin_access_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_admin_access_binding_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.AdminAccessBinding() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + admin_access_binding=resources.AdminAccessBinding( + user_email="user_email_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.AdminAccessBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_admin_access_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=organizations/*}/adminAccessBindings" + % client.transport._host, + args[1], + ) + + +def test_create_admin_access_binding_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.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_admin_access_binding( + marketingplatform_admin.CreateAdminAccessBindingRequest(), + parent="parent_value", + admin_access_binding=resources.AdminAccessBinding( + user_email="user_email_value" + ), + ) + + +def test_update_admin_access_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_admin_access_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_admin_access_binding + ] = mock_rpc + + request = {} + client.update_admin_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_admin_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_admin_access_binding_rest_required_fields( + request_type=marketingplatform_admin.UpdateAdminAccessBindingRequest, +): + transport_class = transports.MarketingplatformAdminServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateAdminAccessBinding, + "_BaseUpdateAdminAccessBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("updateMask",)) + + # verify required fields with non-default values are left alone + + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.AdminAccessBinding() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.AdminAccessBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_admin_access_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_admin_access_binding_rest_flattened(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.AdminAccessBinding() + + # get arguments that satisfy an http rule for this method + sample_request = { + "admin_access_binding": { + "name": "organizations/sample1/adminAccessBindings/sample2" + } + } + + # get truthy value for each flattened field + mock_args = dict( + admin_access_binding=resources.AdminAccessBinding( + user_email="user_email_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.AdminAccessBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_admin_access_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{admin_access_binding.name=organizations/*/adminAccessBindings/*}" + % client.transport._host, + args[1], + ) + + +def test_update_admin_access_binding_rest_flattened_error(transport: str = "rest"): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.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_admin_access_binding( + marketingplatform_admin.UpdateAdminAccessBindingRequest(), + admin_access_binding=resources.AdminAccessBinding( + user_email="user_email_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.MarketingplatformAdminServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.MarketingplatformAdminServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = MarketingplatformAdminServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.MarketingplatformAdminServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = MarketingplatformAdminServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = MarketingplatformAdminServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.MarketingplatformAdminServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = MarketingplatformAdminServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.MarketingplatformAdminServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = MarketingplatformAdminServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.MarketingplatformAdminServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.MarketingplatformAdminServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.MarketingplatformAdminServiceGrpcTransport, + transports.MarketingplatformAdminServiceGrpcAsyncIOTransport, + transports.MarketingplatformAdminServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = MarketingplatformAdminServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_organization_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_organization), "__call__") as call: + call.return_value = resources.Organization() + client.get_organization(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.GetOrganizationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_organizations_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_organizations), "__call__" + ) as call: + call.return_value = marketingplatform_admin.ListOrganizationsResponse() + client.list_organizations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.ListOrganizationsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_find_sales_partner_managed_clients_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.find_sales_partner_managed_clients), "__call__" + ) as call: + call.return_value = ( + marketingplatform_admin.FindSalesPartnerManagedClientsResponse() + ) + client.find_sales_partner_managed_clients(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.FindSalesPartnerManagedClientsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_analytics_account_links_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_analytics_account_links), "__call__" + ) as call: + call.return_value = marketingplatform_admin.ListAnalyticsAccountLinksResponse() + client.list_analytics_account_links(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.ListAnalyticsAccountLinksRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_analytics_account_link_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_analytics_account_link), "__call__" + ) as call: + call.return_value = resources.AnalyticsAccountLink() + client.create_analytics_account_link(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.CreateAnalyticsAccountLinkRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_analytics_account_link_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_analytics_account_link), "__call__" + ) as call: + call.return_value = None + client.delete_analytics_account_link(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.DeleteAnalyticsAccountLinkRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_property_service_level_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_property_service_level), "__call__" + ) as call: + call.return_value = marketingplatform_admin.SetPropertyServiceLevelResponse() + client.set_property_service_level(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.SetPropertyServiceLevelRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_report_property_usage_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.report_property_usage), "__call__" + ) as call: + call.return_value = marketingplatform_admin.ReportPropertyUsageResponse() + client.report_property_usage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.ReportPropertyUsageRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_user_group_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_user_group), "__call__") as call: + call.return_value = resources.UserGroup() + client.get_user_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.GetUserGroupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_user_groups_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_user_groups), "__call__") as call: + call.return_value = marketingplatform_admin.ListUserGroupsResponse() + client.list_user_groups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.ListUserGroupsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_user_group_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user_group), "__call__" + ) as call: + call.return_value = resources.UserGroup() + client.create_user_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.CreateUserGroupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_user_group_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user_group), "__call__" + ) as call: + call.return_value = resources.UserGroup() + client.update_user_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.UpdateUserGroupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_user_group_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_group), "__call__" + ) as call: + call.return_value = None + client.delete_user_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.DeleteUserGroupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_user_group_member_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user_group_member), "__call__" + ) as call: + call.return_value = resources.UserGroupMember() + client.get_user_group_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.GetUserGroupMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_user_group_members_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_user_group_members), "__call__" + ) as call: + call.return_value = marketingplatform_admin.ListUserGroupMembersResponse() + client.list_user_group_members(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.ListUserGroupMembersRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_user_group_member_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user_group_member), "__call__" + ) as call: + call.return_value = resources.UserGroupMember() + client.create_user_group_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.CreateUserGroupMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_user_group_member_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user_group_member), "__call__" + ) as call: + call.return_value = resources.UserGroupMember() + client.update_user_group_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.UpdateUserGroupMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_user_group_member_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_group_member), "__call__" + ) as call: + call.return_value = None + client.delete_user_group_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.DeleteUserGroupMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_admin_access_binding_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_admin_access_binding), "__call__" + ) as call: + call.return_value = resources.AdminAccessBinding() + client.get_admin_access_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.GetAdminAccessBindingRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_admin_access_bindings_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_admin_access_bindings), "__call__" + ) as call: + call.return_value = marketingplatform_admin.ListAdminAccessBindingsResponse() + client.list_admin_access_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.ListAdminAccessBindingsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_admin_access_binding_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_admin_access_binding), "__call__" + ) as call: + call.return_value = resources.AdminAccessBinding() + client.create_admin_access_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.CreateAdminAccessBindingRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_admin_access_binding_empty_call_grpc(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_admin_access_binding), "__call__" + ) as call: + call.return_value = resources.AdminAccessBinding() + client.update_admin_access_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.UpdateAdminAccessBindingRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = MarketingplatformAdminServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_organization_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_organization), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Organization( + name="name_value", + display_name="display_name_value", + ) + ) + await client.get_organization(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.GetOrganizationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_organizations_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_organizations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + marketingplatform_admin.ListOrganizationsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_organizations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.ListOrganizationsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_find_sales_partner_managed_clients_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.find_sales_partner_managed_clients), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + marketingplatform_admin.FindSalesPartnerManagedClientsResponse() + ) + await client.find_sales_partner_managed_clients(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.FindSalesPartnerManagedClientsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_analytics_account_links_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_analytics_account_links), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + marketingplatform_admin.ListAnalyticsAccountLinksResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_analytics_account_links(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.ListAnalyticsAccountLinksRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_analytics_account_link_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_analytics_account_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AnalyticsAccountLink( + name="name_value", + analytics_account="analytics_account_value", + display_name="display_name_value", + link_verification_state=resources.LinkVerificationState.LINK_VERIFICATION_STATE_VERIFIED, + ) + ) + await client.create_analytics_account_link(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.CreateAnalyticsAccountLinkRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_analytics_account_link_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_analytics_account_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_analytics_account_link(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.DeleteAnalyticsAccountLinkRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_set_property_service_level_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_property_service_level), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + marketingplatform_admin.SetPropertyServiceLevelResponse() + ) + await client.set_property_service_level(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.SetPropertyServiceLevelRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_report_property_usage_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.report_property_usage), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + marketingplatform_admin.ReportPropertyUsageResponse() + ) + await client.report_property_usage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.ReportPropertyUsageRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_user_group_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_user_group), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.UserGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + ) + await client.get_user_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.GetUserGroupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_user_groups_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_user_groups), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + marketingplatform_admin.ListUserGroupsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_user_groups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.ListUserGroupsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_user_group_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.UserGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + ) + await client.create_user_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.CreateUserGroupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_user_group_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.UserGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + ) + await client.update_user_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.UpdateUserGroupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_user_group_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.DeleteUserGroupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_user_group_member_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user_group_member), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.UserGroupMember( + name="name_value", + membership_role=resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER, + ) + ) + await client.get_user_group_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.GetUserGroupMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_user_group_members_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_user_group_members), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + marketingplatform_admin.ListUserGroupMembersResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_user_group_members(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.ListUserGroupMembersRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_user_group_member_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user_group_member), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.UserGroupMember( + name="name_value", + membership_role=resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER, + ) + ) + await client.create_user_group_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.CreateUserGroupMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_user_group_member_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user_group_member), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.UserGroupMember( + name="name_value", + membership_role=resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER, + ) + ) + await client.update_user_group_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.UpdateUserGroupMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_user_group_member_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_group_member), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user_group_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.DeleteUserGroupMemberRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_admin_access_binding_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_admin_access_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AdminAccessBinding( + name="name_value", + organization_roles=[resources.OrganizationRole.ORG_ADMIN_ROLE], + ) + ) + await client.get_admin_access_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.GetAdminAccessBindingRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_admin_access_bindings_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_admin_access_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + marketingplatform_admin.ListAdminAccessBindingsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_admin_access_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.ListAdminAccessBindingsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_admin_access_binding_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_admin_access_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AdminAccessBinding( + name="name_value", + organization_roles=[resources.OrganizationRole.ORG_ADMIN_ROLE], + ) + ) + await client.create_admin_access_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.CreateAdminAccessBindingRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_admin_access_binding_empty_call_grpc_asyncio(): + client = MarketingplatformAdminServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_admin_access_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AdminAccessBinding( + name="name_value", + organization_roles=[resources.OrganizationRole.ORG_ADMIN_ROLE], + ) + ) + await client.update_admin_access_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.UpdateAdminAccessBindingRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = MarketingplatformAdminServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_organization_rest_bad_request( + request_type=marketingplatform_admin.GetOrganizationRequest, +): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_organization(request) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.GetOrganizationRequest, + dict, + ], +) +def test_get_organization_rest_call_success(request_type): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Organization( + name="name_value", + display_name="display_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.Organization.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_organization(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Organization) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_organization_rest_interceptors(null_interceptor): + transport = transports.MarketingplatformAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MarketingplatformAdminServiceRestInterceptor(), + ) + client = MarketingplatformAdminServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_get_organization", + ) as post, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_get_organization_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "pre_get_organization", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = marketingplatform_admin.GetOrganizationRequest.pb( + marketingplatform_admin.GetOrganizationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = resources.Organization.to_json(resources.Organization()) + req.return_value.content = return_value + + request = marketingplatform_admin.GetOrganizationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Organization() + post_with_metadata.return_value = resources.Organization(), metadata + + client.get_organization( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_organizations_rest_bad_request( + request_type=marketingplatform_admin.ListOrganizationsRequest, +): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_organizations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.ListOrganizationsRequest, + dict, + ], +) +def test_list_organizations_rest_call_success(request_type): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = marketingplatform_admin.ListOrganizationsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = marketingplatform_admin.ListOrganizationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_organizations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOrganizationsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_organizations_rest_interceptors(null_interceptor): + transport = transports.MarketingplatformAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MarketingplatformAdminServiceRestInterceptor(), + ) + client = MarketingplatformAdminServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_list_organizations", + ) as post, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_list_organizations_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "pre_list_organizations", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = marketingplatform_admin.ListOrganizationsRequest.pb( + marketingplatform_admin.ListOrganizationsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = marketingplatform_admin.ListOrganizationsResponse.to_json( + marketingplatform_admin.ListOrganizationsResponse() + ) + req.return_value.content = return_value + + request = marketingplatform_admin.ListOrganizationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = marketingplatform_admin.ListOrganizationsResponse() + post_with_metadata.return_value = ( + marketingplatform_admin.ListOrganizationsResponse(), + metadata, + ) + + client.list_organizations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_find_sales_partner_managed_clients_rest_bad_request( + request_type=marketingplatform_admin.FindSalesPartnerManagedClientsRequest, +): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.find_sales_partner_managed_clients(request) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.FindSalesPartnerManagedClientsRequest, + dict, + ], +) +def test_find_sales_partner_managed_clients_rest_call_success(request_type): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = marketingplatform_admin.FindSalesPartnerManagedClientsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + marketingplatform_admin.FindSalesPartnerManagedClientsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.find_sales_partner_managed_clients(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, marketingplatform_admin.FindSalesPartnerManagedClientsResponse + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_find_sales_partner_managed_clients_rest_interceptors(null_interceptor): + transport = transports.MarketingplatformAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MarketingplatformAdminServiceRestInterceptor(), + ) + client = MarketingplatformAdminServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_find_sales_partner_managed_clients", + ) as post, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_find_sales_partner_managed_clients_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "pre_find_sales_partner_managed_clients", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = marketingplatform_admin.FindSalesPartnerManagedClientsRequest.pb( + marketingplatform_admin.FindSalesPartnerManagedClientsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = ( + marketingplatform_admin.FindSalesPartnerManagedClientsResponse.to_json( + marketingplatform_admin.FindSalesPartnerManagedClientsResponse() + ) + ) + req.return_value.content = return_value + + request = marketingplatform_admin.FindSalesPartnerManagedClientsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + marketingplatform_admin.FindSalesPartnerManagedClientsResponse() + ) + post_with_metadata.return_value = ( + marketingplatform_admin.FindSalesPartnerManagedClientsResponse(), + metadata, + ) + + client.find_sales_partner_managed_clients( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_analytics_account_links_rest_bad_request( + request_type=marketingplatform_admin.ListAnalyticsAccountLinksRequest, +): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_analytics_account_links(request) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.ListAnalyticsAccountLinksRequest, + dict, + ], +) +def test_list_analytics_account_links_rest_call_success(request_type): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = marketingplatform_admin.ListAnalyticsAccountLinksResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = marketingplatform_admin.ListAnalyticsAccountLinksResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_analytics_account_links(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAnalyticsAccountLinksPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_analytics_account_links_rest_interceptors(null_interceptor): + transport = transports.MarketingplatformAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MarketingplatformAdminServiceRestInterceptor(), + ) + client = MarketingplatformAdminServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_list_analytics_account_links", + ) as post, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_list_analytics_account_links_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "pre_list_analytics_account_links", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = marketingplatform_admin.ListAnalyticsAccountLinksRequest.pb( + marketingplatform_admin.ListAnalyticsAccountLinksRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = ( + marketingplatform_admin.ListAnalyticsAccountLinksResponse.to_json( + marketingplatform_admin.ListAnalyticsAccountLinksResponse() + ) + ) + req.return_value.content = return_value + + request = marketingplatform_admin.ListAnalyticsAccountLinksRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = marketingplatform_admin.ListAnalyticsAccountLinksResponse() + post_with_metadata.return_value = ( + marketingplatform_admin.ListAnalyticsAccountLinksResponse(), + metadata, + ) + + client.list_analytics_account_links( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_analytics_account_link_rest_bad_request( + request_type=marketingplatform_admin.CreateAnalyticsAccountLinkRequest, +): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_analytics_account_link(request) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.CreateAnalyticsAccountLinkRequest, + dict, + ], +) +def test_create_analytics_account_link_rest_call_success(request_type): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request_init["analytics_account_link"] = { + "name": "name_value", + "analytics_account": "analytics_account_value", + "display_name": "display_name_value", + "link_verification_state": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = marketingplatform_admin.CreateAnalyticsAccountLinkRequest.meta.fields[ + "analytics_account_link" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "analytics_account_link" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["analytics_account_link"][field])): + del request_init["analytics_account_link"][field][i][subfield] + else: + del request_init["analytics_account_link"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.AnalyticsAccountLink( + name="name_value", + analytics_account="analytics_account_value", + display_name="display_name_value", + link_verification_state=resources.LinkVerificationState.LINK_VERIFICATION_STATE_VERIFIED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.AnalyticsAccountLink.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_analytics_account_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AnalyticsAccountLink) + assert response.name == "name_value" + assert response.analytics_account == "analytics_account_value" + assert response.display_name == "display_name_value" + assert ( + response.link_verification_state + == resources.LinkVerificationState.LINK_VERIFICATION_STATE_VERIFIED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_analytics_account_link_rest_interceptors(null_interceptor): + transport = transports.MarketingplatformAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MarketingplatformAdminServiceRestInterceptor(), + ) + client = MarketingplatformAdminServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_create_analytics_account_link", + ) as post, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_create_analytics_account_link_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "pre_create_analytics_account_link", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = marketingplatform_admin.CreateAnalyticsAccountLinkRequest.pb( + marketingplatform_admin.CreateAnalyticsAccountLinkRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = resources.AnalyticsAccountLink.to_json( + resources.AnalyticsAccountLink() + ) + req.return_value.content = return_value + + request = marketingplatform_admin.CreateAnalyticsAccountLinkRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.AnalyticsAccountLink() + post_with_metadata.return_value = resources.AnalyticsAccountLink(), metadata + + client.create_analytics_account_link( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_analytics_account_link_rest_bad_request( + request_type=marketingplatform_admin.DeleteAnalyticsAccountLinkRequest, +): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/analyticsAccountLinks/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_analytics_account_link(request) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.DeleteAnalyticsAccountLinkRequest, + dict, + ], +) +def test_delete_analytics_account_link_rest_call_success(request_type): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/analyticsAccountLinks/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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_analytics_account_link(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_analytics_account_link_rest_interceptors(null_interceptor): + transport = transports.MarketingplatformAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MarketingplatformAdminServiceRestInterceptor(), + ) + client = MarketingplatformAdminServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "pre_delete_analytics_account_link", + ) as pre, + ): + pre.assert_not_called() + pb_message = marketingplatform_admin.DeleteAnalyticsAccountLinkRequest.pb( + marketingplatform_admin.DeleteAnalyticsAccountLinkRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = marketingplatform_admin.DeleteAnalyticsAccountLinkRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_analytics_account_link( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_set_property_service_level_rest_bad_request( + request_type=marketingplatform_admin.SetPropertyServiceLevelRequest, +): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "analytics_account_link": "organizations/sample1/analyticsAccountLinks/sample2" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_property_service_level(request) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.SetPropertyServiceLevelRequest, + dict, + ], +) +def test_set_property_service_level_rest_call_success(request_type): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "analytics_account_link": "organizations/sample1/analyticsAccountLinks/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 = marketingplatform_admin.SetPropertyServiceLevelResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = marketingplatform_admin.SetPropertyServiceLevelResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.set_property_service_level(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, marketingplatform_admin.SetPropertyServiceLevelResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_property_service_level_rest_interceptors(null_interceptor): + transport = transports.MarketingplatformAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MarketingplatformAdminServiceRestInterceptor(), + ) + client = MarketingplatformAdminServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_set_property_service_level", + ) as post, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_set_property_service_level_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "pre_set_property_service_level", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = marketingplatform_admin.SetPropertyServiceLevelRequest.pb( + marketingplatform_admin.SetPropertyServiceLevelRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = marketingplatform_admin.SetPropertyServiceLevelResponse.to_json( + marketingplatform_admin.SetPropertyServiceLevelResponse() + ) + req.return_value.content = return_value + + request = marketingplatform_admin.SetPropertyServiceLevelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = marketingplatform_admin.SetPropertyServiceLevelResponse() + post_with_metadata.return_value = ( + marketingplatform_admin.SetPropertyServiceLevelResponse(), + metadata, + ) + + client.set_property_service_level( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_report_property_usage_rest_bad_request( + request_type=marketingplatform_admin.ReportPropertyUsageRequest, +): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.report_property_usage(request) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.ReportPropertyUsageRequest, + dict, + ], +) +def test_report_property_usage_rest_call_success(request_type): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = marketingplatform_admin.ReportPropertyUsageResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = marketingplatform_admin.ReportPropertyUsageResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.report_property_usage(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, marketingplatform_admin.ReportPropertyUsageResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_report_property_usage_rest_interceptors(null_interceptor): + transport = transports.MarketingplatformAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MarketingplatformAdminServiceRestInterceptor(), + ) + client = MarketingplatformAdminServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_report_property_usage", + ) as post, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_report_property_usage_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "pre_report_property_usage", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = marketingplatform_admin.ReportPropertyUsageRequest.pb( + marketingplatform_admin.ReportPropertyUsageRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = marketingplatform_admin.ReportPropertyUsageResponse.to_json( + marketingplatform_admin.ReportPropertyUsageResponse() + ) + req.return_value.content = return_value + + request = marketingplatform_admin.ReportPropertyUsageRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = marketingplatform_admin.ReportPropertyUsageResponse() + post_with_metadata.return_value = ( + marketingplatform_admin.ReportPropertyUsageResponse(), + metadata, + ) + + client.report_property_usage( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_user_group_rest_bad_request( + request_type=marketingplatform_admin.GetUserGroupRequest, +): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/userGroups/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_user_group(request) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.GetUserGroupRequest, + dict, + ], +) +def test_get_user_group_rest_call_success(request_type): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/userGroups/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 = resources.UserGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.UserGroup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_user_group(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.UserGroup) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_user_group_rest_interceptors(null_interceptor): + transport = transports.MarketingplatformAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MarketingplatformAdminServiceRestInterceptor(), + ) + client = MarketingplatformAdminServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_get_user_group", + ) as post, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_get_user_group_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "pre_get_user_group", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = marketingplatform_admin.GetUserGroupRequest.pb( + marketingplatform_admin.GetUserGroupRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = resources.UserGroup.to_json(resources.UserGroup()) + req.return_value.content = return_value + + request = marketingplatform_admin.GetUserGroupRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.UserGroup() + post_with_metadata.return_value = resources.UserGroup(), metadata + + client.get_user_group( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_user_groups_rest_bad_request( + request_type=marketingplatform_admin.ListUserGroupsRequest, +): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_user_groups(request) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.ListUserGroupsRequest, + dict, + ], +) +def test_list_user_groups_rest_call_success(request_type): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = marketingplatform_admin.ListUserGroupsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = marketingplatform_admin.ListUserGroupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_user_groups(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserGroupsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_user_groups_rest_interceptors(null_interceptor): + transport = transports.MarketingplatformAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MarketingplatformAdminServiceRestInterceptor(), + ) + client = MarketingplatformAdminServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_list_user_groups", + ) as post, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_list_user_groups_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "pre_list_user_groups", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = marketingplatform_admin.ListUserGroupsRequest.pb( + marketingplatform_admin.ListUserGroupsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = marketingplatform_admin.ListUserGroupsResponse.to_json( + marketingplatform_admin.ListUserGroupsResponse() + ) + req.return_value.content = return_value + + request = marketingplatform_admin.ListUserGroupsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = marketingplatform_admin.ListUserGroupsResponse() + post_with_metadata.return_value = ( + marketingplatform_admin.ListUserGroupsResponse(), + metadata, + ) + + client.list_user_groups( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_user_group_rest_bad_request( + request_type=marketingplatform_admin.CreateUserGroupRequest, +): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_user_group(request) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.CreateUserGroupRequest, + dict, + ], +) +def test_create_user_group_rest_call_success(request_type): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request_init["user_group"] = { + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = marketingplatform_admin.CreateUserGroupRequest.meta.fields[ + "user_group" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["user_group"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["user_group"][field])): + del request_init["user_group"][field][i][subfield] + else: + del request_init["user_group"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.UserGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.UserGroup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_user_group(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.UserGroup) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_user_group_rest_interceptors(null_interceptor): + transport = transports.MarketingplatformAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MarketingplatformAdminServiceRestInterceptor(), + ) + client = MarketingplatformAdminServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_create_user_group", + ) as post, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_create_user_group_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "pre_create_user_group", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = marketingplatform_admin.CreateUserGroupRequest.pb( + marketingplatform_admin.CreateUserGroupRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = resources.UserGroup.to_json(resources.UserGroup()) + req.return_value.content = return_value + + request = marketingplatform_admin.CreateUserGroupRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.UserGroup() + post_with_metadata.return_value = resources.UserGroup(), metadata + + client.create_user_group( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_user_group_rest_bad_request( + request_type=marketingplatform_admin.UpdateUserGroupRequest, +): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"user_group": {"name": "organizations/sample1/userGroups/sample2"}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_user_group(request) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.UpdateUserGroupRequest, + dict, + ], +) +def test_update_user_group_rest_call_success(request_type): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"user_group": {"name": "organizations/sample1/userGroups/sample2"}} + request_init["user_group"] = { + "name": "organizations/sample1/userGroups/sample2", + "display_name": "display_name_value", + "description": "description_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = marketingplatform_admin.UpdateUserGroupRequest.meta.fields[ + "user_group" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["user_group"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["user_group"][field])): + del request_init["user_group"][field][i][subfield] + else: + del request_init["user_group"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.UserGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.UserGroup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_user_group(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.UserGroup) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_user_group_rest_interceptors(null_interceptor): + transport = transports.MarketingplatformAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MarketingplatformAdminServiceRestInterceptor(), + ) + client = MarketingplatformAdminServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_update_user_group", + ) as post, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_update_user_group_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "pre_update_user_group", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = marketingplatform_admin.UpdateUserGroupRequest.pb( + marketingplatform_admin.UpdateUserGroupRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = resources.UserGroup.to_json(resources.UserGroup()) + req.return_value.content = return_value + + request = marketingplatform_admin.UpdateUserGroupRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.UserGroup() + post_with_metadata.return_value = resources.UserGroup(), metadata + + client.update_user_group( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_user_group_rest_bad_request( + request_type=marketingplatform_admin.DeleteUserGroupRequest, +): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/userGroups/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_user_group(request) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.DeleteUserGroupRequest, + dict, + ], +) +def test_delete_user_group_rest_call_success(request_type): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/userGroups/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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_user_group(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_user_group_rest_interceptors(null_interceptor): + transport = transports.MarketingplatformAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MarketingplatformAdminServiceRestInterceptor(), + ) + client = MarketingplatformAdminServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "pre_delete_user_group", + ) as pre, + ): + pre.assert_not_called() + pb_message = marketingplatform_admin.DeleteUserGroupRequest.pb( + marketingplatform_admin.DeleteUserGroupRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = marketingplatform_admin.DeleteUserGroupRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_user_group( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_get_user_group_member_rest_bad_request( + request_type=marketingplatform_admin.GetUserGroupMemberRequest, +): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/userGroups/sample2/members/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_user_group_member(request) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.GetUserGroupMemberRequest, + dict, + ], +) +def test_get_user_group_member_rest_call_success(request_type): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/userGroups/sample2/members/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.UserGroupMember( + name="name_value", + membership_role=resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER, + user_email="user_email_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.UserGroupMember.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_user_group_member(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.UserGroupMember) + assert response.name == "name_value" + assert ( + response.membership_role + == resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_user_group_member_rest_interceptors(null_interceptor): + transport = transports.MarketingplatformAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MarketingplatformAdminServiceRestInterceptor(), + ) + client = MarketingplatformAdminServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_get_user_group_member", + ) as post, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_get_user_group_member_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "pre_get_user_group_member", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = marketingplatform_admin.GetUserGroupMemberRequest.pb( + marketingplatform_admin.GetUserGroupMemberRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = resources.UserGroupMember.to_json(resources.UserGroupMember()) + req.return_value.content = return_value + + request = marketingplatform_admin.GetUserGroupMemberRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.UserGroupMember() + post_with_metadata.return_value = resources.UserGroupMember(), metadata + + client.get_user_group_member( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_user_group_members_rest_bad_request( + request_type=marketingplatform_admin.ListUserGroupMembersRequest, +): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/userGroups/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_user_group_members(request) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.ListUserGroupMembersRequest, + dict, + ], +) +def test_list_user_group_members_rest_call_success(request_type): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/userGroups/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 = marketingplatform_admin.ListUserGroupMembersResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = marketingplatform_admin.ListUserGroupMembersResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_user_group_members(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserGroupMembersPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_user_group_members_rest_interceptors(null_interceptor): + transport = transports.MarketingplatformAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MarketingplatformAdminServiceRestInterceptor(), + ) + client = MarketingplatformAdminServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_list_user_group_members", + ) as post, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_list_user_group_members_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "pre_list_user_group_members", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = marketingplatform_admin.ListUserGroupMembersRequest.pb( + marketingplatform_admin.ListUserGroupMembersRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = marketingplatform_admin.ListUserGroupMembersResponse.to_json( + marketingplatform_admin.ListUserGroupMembersResponse() + ) + req.return_value.content = return_value + + request = marketingplatform_admin.ListUserGroupMembersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = marketingplatform_admin.ListUserGroupMembersResponse() + post_with_metadata.return_value = ( + marketingplatform_admin.ListUserGroupMembersResponse(), + metadata, + ) + + client.list_user_group_members( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_user_group_member_rest_bad_request( + request_type=marketingplatform_admin.CreateUserGroupMemberRequest, +): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/userGroups/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_user_group_member(request) + + +@pytest.mark.parametrize( + "request_type", + [ + marketingplatform_admin.CreateUserGroupMemberRequest, + dict, + ], +) +def test_create_user_group_member_rest_call_success(request_type): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/userGroups/sample2"} + request_init["user_group_member"] = { + "user_email": "user_email_value", + "user_group": "user_group_value", + "name": "name_value", + "membership_role": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = marketingplatform_admin.CreateUserGroupMemberRequest.meta.fields[ + "user_group_member" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["user_group_member"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["user_group_member"][field])): + del request_init["user_group_member"][field][i][subfield] + else: + del request_init["user_group_member"][field][subfield] + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.UserGroupMember( + name="name_value", + membership_role=resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER, + user_email="user_email_value", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_set_property_service_level_empty_call_grpc_asyncio(): - client = MarketingplatformAdminServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.set_property_service_level), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - marketingplatform_admin.SetPropertyServiceLevelResponse() - ) - await client.set_property_service_level(request=None) + # Convert return value to protobuf type + return_value = resources.UserGroupMember.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_user_group_member(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.SetPropertyServiceLevelRequest() - assert args[0] == request_msg + # Establish that the response is the type that we expect. + assert isinstance(response, resources.UserGroupMember) + assert response.name == "name_value" + assert ( + response.membership_role + == resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_report_property_usage_empty_call_grpc_asyncio(): - client = MarketingplatformAdminServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_user_group_member_rest_interceptors(null_interceptor): + transport = transports.MarketingplatformAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MarketingplatformAdminServiceRestInterceptor(), ) + client = MarketingplatformAdminServiceClient(transport=transport) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.report_property_usage), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - marketingplatform_admin.ReportPropertyUsageResponse() + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_create_user_group_member", + ) as post, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "post_create_user_group_member_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MarketingplatformAdminServiceRestInterceptor, + "pre_create_user_group_member", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = marketingplatform_admin.CreateUserGroupMemberRequest.pb( + marketingplatform_admin.CreateUserGroupMemberRequest() ) - await client.report_property_usage(request=None) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.ReportPropertyUsageRequest() - assert args[0] == request_msg + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = resources.UserGroupMember.to_json(resources.UserGroupMember()) + req.return_value.content = return_value + request = marketingplatform_admin.CreateUserGroupMemberRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.UserGroupMember() + post_with_metadata.return_value = resources.UserGroupMember(), metadata -def test_transport_kind_rest(): - transport = MarketingplatformAdminServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + client.create_user_group_member( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_get_organization_rest_bad_request( - request_type=marketingplatform_admin.GetOrganizationRequest, + +def test_update_user_group_member_rest_bad_request( + request_type=marketingplatform_admin.UpdateUserGroupMemberRequest, ): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "organizations/sample1"} + request_init = { + "user_group_member": { + "name": "organizations/sample1/userGroups/sample2/members/sample3" + } + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -5955,31 +17286,111 @@ def test_get_organization_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_organization(request) + client.update_user_group_member(request) @pytest.mark.parametrize( "request_type", [ - marketingplatform_admin.GetOrganizationRequest, + marketingplatform_admin.UpdateUserGroupMemberRequest, dict, ], ) -def test_get_organization_rest_call_success(request_type): +def test_update_user_group_member_rest_call_success(request_type): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "organizations/sample1"} + request_init = { + "user_group_member": { + "name": "organizations/sample1/userGroups/sample2/members/sample3" + } + } + request_init["user_group_member"] = { + "user_email": "user_email_value", + "user_group": "user_group_value", + "name": "organizations/sample1/userGroups/sample2/members/sample3", + "membership_role": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = marketingplatform_admin.UpdateUserGroupMemberRequest.meta.fields[ + "user_group_member" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["user_group_member"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["user_group_member"][field])): + del request_init["user_group_member"][field][i][subfield] + else: + del request_init["user_group_member"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Organization( + return_value = resources.UserGroupMember( name="name_value", - display_name="display_name_value", + membership_role=resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER, + user_email="user_email_value", ) # Wrap the value into a proper Response obj @@ -5987,21 +17398,24 @@ def test_get_organization_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Organization.pb(return_value) + return_value = resources.UserGroupMember.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_organization(request) + response = client.update_user_group_member(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.Organization) + assert isinstance(response, resources.UserGroupMember) assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert ( + response.membership_role + == resources.UserGroupMember.MembershipRole.MEMBERSHIP_ROLE_OWNER + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_organization_rest_interceptors(null_interceptor): +def test_update_user_group_member_rest_interceptors(null_interceptor): transport = transports.MarketingplatformAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6015,22 +17429,22 @@ def test_get_organization_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.MarketingplatformAdminServiceRestInterceptor, - "post_get_organization", + "post_update_user_group_member", ) as post, mock.patch.object( transports.MarketingplatformAdminServiceRestInterceptor, - "post_get_organization_with_metadata", + "post_update_user_group_member_with_metadata", ) as post_with_metadata, mock.patch.object( transports.MarketingplatformAdminServiceRestInterceptor, - "pre_get_organization", + "pre_update_user_group_member", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = marketingplatform_admin.GetOrganizationRequest.pb( - marketingplatform_admin.GetOrganizationRequest() + pb_message = marketingplatform_admin.UpdateUserGroupMemberRequest.pb( + marketingplatform_admin.UpdateUserGroupMemberRequest() ) transcode.return_value = { "method": "post", @@ -6042,19 +17456,19 @@ def test_get_organization_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resources.Organization.to_json(resources.Organization()) + return_value = resources.UserGroupMember.to_json(resources.UserGroupMember()) req.return_value.content = return_value - request = marketingplatform_admin.GetOrganizationRequest() + request = marketingplatform_admin.UpdateUserGroupMemberRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.Organization() - post_with_metadata.return_value = resources.Organization(), metadata + post.return_value = resources.UserGroupMember() + post_with_metadata.return_value = resources.UserGroupMember(), metadata - client.get_organization( + client.update_user_group_member( request, metadata=[ ("key", "val"), @@ -6067,14 +17481,14 @@ def test_get_organization_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_organizations_rest_bad_request( - request_type=marketingplatform_admin.ListOrganizationsRequest, +def test_delete_user_group_member_rest_bad_request( + request_type=marketingplatform_admin.DeleteUserGroupMemberRequest, ): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"name": "organizations/sample1/userGroups/sample2/members/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -6090,53 +17504,45 @@ def test_list_organizations_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_organizations(request) + client.delete_user_group_member(request) @pytest.mark.parametrize( "request_type", [ - marketingplatform_admin.ListOrganizationsRequest, + marketingplatform_admin.DeleteUserGroupMemberRequest, dict, ], ) -def test_list_organizations_rest_call_success(request_type): +def test_delete_user_group_member_rest_call_success(request_type): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"name": "organizations/sample1/userGroups/sample2/members/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 = marketingplatform_admin.ListOrganizationsResponse( - next_page_token="next_page_token_value", - ) + return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = marketingplatform_admin.ListOrganizationsResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_organizations(request) + response = client.delete_user_group_member(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListOrganizationsPager) - assert response.next_page_token == "next_page_token_value" + assert response is None @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_organizations_rest_interceptors(null_interceptor): +def test_delete_user_group_member_rest_interceptors(null_interceptor): transport = transports.MarketingplatformAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6150,22 +17556,12 @@ def test_list_organizations_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.MarketingplatformAdminServiceRestInterceptor, - "post_list_organizations", - ) as post, - mock.patch.object( - transports.MarketingplatformAdminServiceRestInterceptor, - "post_list_organizations_with_metadata", - ) as post_with_metadata, - mock.patch.object( - transports.MarketingplatformAdminServiceRestInterceptor, - "pre_list_organizations", + "pre_delete_user_group_member", ) as pre, ): pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = marketingplatform_admin.ListOrganizationsRequest.pb( - marketingplatform_admin.ListOrganizationsRequest() + pb_message = marketingplatform_admin.DeleteUserGroupMemberRequest.pb( + marketingplatform_admin.DeleteUserGroupMemberRequest() ) transcode.return_value = { "method": "post", @@ -6177,24 +17573,15 @@ def test_list_organizations_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = marketingplatform_admin.ListOrganizationsResponse.to_json( - marketingplatform_admin.ListOrganizationsResponse() - ) - req.return_value.content = return_value - request = marketingplatform_admin.ListOrganizationsRequest() + request = marketingplatform_admin.DeleteUserGroupMemberRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = marketingplatform_admin.ListOrganizationsResponse() - post_with_metadata.return_value = ( - marketingplatform_admin.ListOrganizationsResponse(), - metadata, - ) - client.list_organizations( + client.delete_user_group_member( request, metadata=[ ("key", "val"), @@ -6203,18 +17590,16 @@ def test_list_organizations_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() -def test_find_sales_partner_managed_clients_rest_bad_request( - request_type=marketingplatform_admin.FindSalesPartnerManagedClientsRequest, +def test_get_admin_access_binding_rest_bad_request( + request_type=marketingplatform_admin.GetAdminAccessBindingRequest, ): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"organization": "organizations/sample1"} + request_init = {"name": "organizations/sample1/adminAccessBindings/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -6230,54 +17615,54 @@ def test_find_sales_partner_managed_clients_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.find_sales_partner_managed_clients(request) + client.get_admin_access_binding(request) @pytest.mark.parametrize( "request_type", [ - marketingplatform_admin.FindSalesPartnerManagedClientsRequest, + marketingplatform_admin.GetAdminAccessBindingRequest, dict, ], ) -def test_find_sales_partner_managed_clients_rest_call_success(request_type): +def test_get_admin_access_binding_rest_call_success(request_type): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"organization": "organizations/sample1"} + request_init = {"name": "organizations/sample1/adminAccessBindings/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 = marketingplatform_admin.FindSalesPartnerManagedClientsResponse() + return_value = resources.AdminAccessBinding( + name="name_value", + organization_roles=[resources.OrganizationRole.ORG_ADMIN_ROLE], + user_email="user_email_value", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 # Convert return value to protobuf type - return_value = ( - marketingplatform_admin.FindSalesPartnerManagedClientsResponse.pb( - return_value - ) - ) + return_value = resources.AdminAccessBinding.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.find_sales_partner_managed_clients(request) + response = client.get_admin_access_binding(request) # Establish that the response is the type that we expect. - assert isinstance( - response, marketingplatform_admin.FindSalesPartnerManagedClientsResponse - ) + assert isinstance(response, resources.AdminAccessBinding) + assert response.name == "name_value" + assert response.organization_roles == [resources.OrganizationRole.ORG_ADMIN_ROLE] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_find_sales_partner_managed_clients_rest_interceptors(null_interceptor): +def test_get_admin_access_binding_rest_interceptors(null_interceptor): transport = transports.MarketingplatformAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6291,22 +17676,22 @@ def test_find_sales_partner_managed_clients_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.MarketingplatformAdminServiceRestInterceptor, - "post_find_sales_partner_managed_clients", + "post_get_admin_access_binding", ) as post, mock.patch.object( transports.MarketingplatformAdminServiceRestInterceptor, - "post_find_sales_partner_managed_clients_with_metadata", + "post_get_admin_access_binding_with_metadata", ) as post_with_metadata, mock.patch.object( transports.MarketingplatformAdminServiceRestInterceptor, - "pre_find_sales_partner_managed_clients", + "pre_get_admin_access_binding", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = marketingplatform_admin.FindSalesPartnerManagedClientsRequest.pb( - marketingplatform_admin.FindSalesPartnerManagedClientsRequest() + pb_message = marketingplatform_admin.GetAdminAccessBindingRequest.pb( + marketingplatform_admin.GetAdminAccessBindingRequest() ) transcode.return_value = { "method": "post", @@ -6318,28 +17703,21 @@ def test_find_sales_partner_managed_clients_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = ( - marketingplatform_admin.FindSalesPartnerManagedClientsResponse.to_json( - marketingplatform_admin.FindSalesPartnerManagedClientsResponse() - ) + return_value = resources.AdminAccessBinding.to_json( + resources.AdminAccessBinding() ) req.return_value.content = return_value - request = marketingplatform_admin.FindSalesPartnerManagedClientsRequest() + request = marketingplatform_admin.GetAdminAccessBindingRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = ( - marketingplatform_admin.FindSalesPartnerManagedClientsResponse() - ) - post_with_metadata.return_value = ( - marketingplatform_admin.FindSalesPartnerManagedClientsResponse(), - metadata, - ) + post.return_value = resources.AdminAccessBinding() + post_with_metadata.return_value = resources.AdminAccessBinding(), metadata - client.find_sales_partner_managed_clients( + client.get_admin_access_binding( request, metadata=[ ("key", "val"), @@ -6352,8 +17730,8 @@ def test_find_sales_partner_managed_clients_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_analytics_account_links_rest_bad_request( - request_type=marketingplatform_admin.ListAnalyticsAccountLinksRequest, +def test_list_admin_access_bindings_rest_bad_request( + request_type=marketingplatform_admin.ListAdminAccessBindingsRequest, ): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -6375,17 +17753,17 @@ def test_list_analytics_account_links_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_analytics_account_links(request) + client.list_admin_access_bindings(request) @pytest.mark.parametrize( "request_type", [ - marketingplatform_admin.ListAnalyticsAccountLinksRequest, + marketingplatform_admin.ListAdminAccessBindingsRequest, dict, ], ) -def test_list_analytics_account_links_rest_call_success(request_type): +def test_list_admin_access_bindings_rest_call_success(request_type): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -6397,7 +17775,7 @@ def test_list_analytics_account_links_rest_call_success(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = marketingplatform_admin.ListAnalyticsAccountLinksResponse( + return_value = marketingplatform_admin.ListAdminAccessBindingsResponse( next_page_token="next_page_token_value", ) @@ -6406,22 +17784,22 @@ def test_list_analytics_account_links_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = marketingplatform_admin.ListAnalyticsAccountLinksResponse.pb( + return_value = marketingplatform_admin.ListAdminAccessBindingsResponse.pb( return_value ) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_analytics_account_links(request) + response = client.list_admin_access_bindings(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAnalyticsAccountLinksPager) + assert isinstance(response, pagers.ListAdminAccessBindingsPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_analytics_account_links_rest_interceptors(null_interceptor): +def test_list_admin_access_bindings_rest_interceptors(null_interceptor): transport = transports.MarketingplatformAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6435,22 +17813,22 @@ def test_list_analytics_account_links_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.MarketingplatformAdminServiceRestInterceptor, - "post_list_analytics_account_links", + "post_list_admin_access_bindings", ) as post, mock.patch.object( transports.MarketingplatformAdminServiceRestInterceptor, - "post_list_analytics_account_links_with_metadata", + "post_list_admin_access_bindings_with_metadata", ) as post_with_metadata, mock.patch.object( transports.MarketingplatformAdminServiceRestInterceptor, - "pre_list_analytics_account_links", + "pre_list_admin_access_bindings", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = marketingplatform_admin.ListAnalyticsAccountLinksRequest.pb( - marketingplatform_admin.ListAnalyticsAccountLinksRequest() + pb_message = marketingplatform_admin.ListAdminAccessBindingsRequest.pb( + marketingplatform_admin.ListAdminAccessBindingsRequest() ) transcode.return_value = { "method": "post", @@ -6462,26 +17840,24 @@ def test_list_analytics_account_links_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = ( - marketingplatform_admin.ListAnalyticsAccountLinksResponse.to_json( - marketingplatform_admin.ListAnalyticsAccountLinksResponse() - ) + return_value = marketingplatform_admin.ListAdminAccessBindingsResponse.to_json( + marketingplatform_admin.ListAdminAccessBindingsResponse() ) req.return_value.content = return_value - request = marketingplatform_admin.ListAnalyticsAccountLinksRequest() + request = marketingplatform_admin.ListAdminAccessBindingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = marketingplatform_admin.ListAnalyticsAccountLinksResponse() + post.return_value = marketingplatform_admin.ListAdminAccessBindingsResponse() post_with_metadata.return_value = ( - marketingplatform_admin.ListAnalyticsAccountLinksResponse(), + marketingplatform_admin.ListAdminAccessBindingsResponse(), metadata, ) - client.list_analytics_account_links( + client.list_admin_access_bindings( request, metadata=[ ("key", "val"), @@ -6494,8 +17870,8 @@ def test_list_analytics_account_links_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_analytics_account_link_rest_bad_request( - request_type=marketingplatform_admin.CreateAnalyticsAccountLinkRequest, +def test_create_admin_access_binding_rest_bad_request( + request_type=marketingplatform_admin.CreateAdminAccessBindingRequest, ): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -6517,36 +17893,36 @@ def test_create_analytics_account_link_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_analytics_account_link(request) + client.create_admin_access_binding(request) @pytest.mark.parametrize( "request_type", [ - marketingplatform_admin.CreateAnalyticsAccountLinkRequest, + marketingplatform_admin.CreateAdminAccessBindingRequest, dict, ], ) -def test_create_analytics_account_link_rest_call_success(request_type): +def test_create_admin_access_binding_rest_call_success(request_type): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = {"parent": "organizations/sample1"} - request_init["analytics_account_link"] = { + request_init["admin_access_binding"] = { + "user_email": "user_email_value", + "user_group": "user_group_value", "name": "name_value", - "analytics_account": "analytics_account_value", - "display_name": "display_name_value", - "link_verification_state": 1, + "organization_roles": [1], } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = marketingplatform_admin.CreateAnalyticsAccountLinkRequest.meta.fields[ - "analytics_account_link" + test_field = marketingplatform_admin.CreateAdminAccessBindingRequest.meta.fields[ + "admin_access_binding" ] def get_message_fields(field): @@ -6576,7 +17952,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime for field, value in request_init[ - "analytics_account_link" + "admin_access_binding" ].items(): # pragma: NO COVER result = None is_repeated = False @@ -6607,20 +17983,19 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["analytics_account_link"][field])): - del request_init["analytics_account_link"][field][i][subfield] + for i in range(0, len(request_init["admin_access_binding"][field])): + del request_init["admin_access_binding"][field][i][subfield] else: - del request_init["analytics_account_link"][field][subfield] + del request_init["admin_access_binding"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.AnalyticsAccountLink( + return_value = resources.AdminAccessBinding( name="name_value", - analytics_account="analytics_account_value", - display_name="display_name_value", - link_verification_state=resources.LinkVerificationState.LINK_VERIFICATION_STATE_VERIFIED, + organization_roles=[resources.OrganizationRole.ORG_ADMIN_ROLE], + user_email="user_email_value", ) # Wrap the value into a proper Response obj @@ -6628,26 +18003,21 @@ def get_message_fields(field): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.AnalyticsAccountLink.pb(return_value) + return_value = resources.AdminAccessBinding.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_analytics_account_link(request) + response = client.create_admin_access_binding(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.AnalyticsAccountLink) + assert isinstance(response, resources.AdminAccessBinding) assert response.name == "name_value" - assert response.analytics_account == "analytics_account_value" - assert response.display_name == "display_name_value" - assert ( - response.link_verification_state - == resources.LinkVerificationState.LINK_VERIFICATION_STATE_VERIFIED - ) + assert response.organization_roles == [resources.OrganizationRole.ORG_ADMIN_ROLE] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_analytics_account_link_rest_interceptors(null_interceptor): +def test_create_admin_access_binding_rest_interceptors(null_interceptor): transport = transports.MarketingplatformAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6661,22 +18031,22 @@ def test_create_analytics_account_link_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.MarketingplatformAdminServiceRestInterceptor, - "post_create_analytics_account_link", + "post_create_admin_access_binding", ) as post, mock.patch.object( transports.MarketingplatformAdminServiceRestInterceptor, - "post_create_analytics_account_link_with_metadata", + "post_create_admin_access_binding_with_metadata", ) as post_with_metadata, mock.patch.object( transports.MarketingplatformAdminServiceRestInterceptor, - "pre_create_analytics_account_link", + "pre_create_admin_access_binding", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = marketingplatform_admin.CreateAnalyticsAccountLinkRequest.pb( - marketingplatform_admin.CreateAnalyticsAccountLinkRequest() + pb_message = marketingplatform_admin.CreateAdminAccessBindingRequest.pb( + marketingplatform_admin.CreateAdminAccessBindingRequest() ) transcode.return_value = { "method": "post", @@ -6688,21 +18058,21 @@ def test_create_analytics_account_link_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resources.AnalyticsAccountLink.to_json( - resources.AnalyticsAccountLink() + return_value = resources.AdminAccessBinding.to_json( + resources.AdminAccessBinding() ) req.return_value.content = return_value - request = marketingplatform_admin.CreateAnalyticsAccountLinkRequest() + request = marketingplatform_admin.CreateAdminAccessBindingRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.AnalyticsAccountLink() - post_with_metadata.return_value = resources.AnalyticsAccountLink(), metadata + post.return_value = resources.AdminAccessBinding() + post_with_metadata.return_value = resources.AdminAccessBinding(), metadata - client.create_analytics_account_link( + client.create_admin_access_binding( request, metadata=[ ("key", "val"), @@ -6715,14 +18085,18 @@ def test_create_analytics_account_link_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_analytics_account_link_rest_bad_request( - request_type=marketingplatform_admin.DeleteAnalyticsAccountLinkRequest, +def test_update_admin_access_binding_rest_bad_request( + request_type=marketingplatform_admin.UpdateAdminAccessBindingRequest, ): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "organizations/sample1/analyticsAccountLinks/sample2"} + request_init = { + "admin_access_binding": { + "name": "organizations/sample1/adminAccessBindings/sample2" + } + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -6738,165 +18112,135 @@ def test_delete_analytics_account_link_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_analytics_account_link(request) + client.update_admin_access_binding(request) @pytest.mark.parametrize( "request_type", [ - marketingplatform_admin.DeleteAnalyticsAccountLinkRequest, + marketingplatform_admin.UpdateAdminAccessBindingRequest, dict, ], ) -def test_delete_analytics_account_link_rest_call_success(request_type): +def test_update_admin_access_binding_rest_call_success(request_type): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "organizations/sample1/analyticsAccountLinks/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 = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = "" - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_analytics_account_link(request) - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_analytics_account_link_rest_interceptors(null_interceptor): - transport = transports.MarketingplatformAdminServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.MarketingplatformAdminServiceRestInterceptor(), - ) - client = MarketingplatformAdminServiceClient(transport=transport) - - with ( - mock.patch.object(type(client.transport._session), "request") as req, - mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object( - transports.MarketingplatformAdminServiceRestInterceptor, - "pre_delete_analytics_account_link", - ) as pre, - ): - pre.assert_not_called() - pb_message = marketingplatform_admin.DeleteAnalyticsAccountLinkRequest.pb( - marketingplatform_admin.DeleteAnalyticsAccountLinkRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + request_init = { + "admin_access_binding": { + "name": "organizations/sample1/adminAccessBindings/sample2" } + } + request_init["admin_access_binding"] = { + "user_email": "user_email_value", + "user_group": "user_group_value", + "name": "organizations/sample1/adminAccessBindings/sample2", + "organization_roles": [1], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - request = marketingplatform_admin.DeleteAnalyticsAccountLinkRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_analytics_account_link( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + # Determine if the message type is proto-plus or protobuf + test_field = marketingplatform_admin.UpdateAdminAccessBindingRequest.meta.fields[ + "admin_access_binding" + ] - pre.assert_called_once() + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") -def test_set_property_service_level_rest_bad_request( - request_type=marketingplatform_admin.SetPropertyServiceLevelRequest, -): - client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = { - "analytics_account_link": "organizations/sample1/analyticsAccountLinks/sample2" - } - request = request_type(**request_init) + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.set_property_service_level(request) + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + subfields_not_in_runtime = [] -@pytest.mark.parametrize( - "request_type", - [ - marketingplatform_admin.SetPropertyServiceLevelRequest, - dict, - ], -) -def test_set_property_service_level_rest_call_success(request_type): - client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "admin_access_binding" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value - # send a request that will satisfy transcoding - request_init = { - "analytics_account_link": "organizations/sample1/analyticsAccountLinks/sample2" - } + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["admin_access_binding"][field])): + del request_init["admin_access_binding"][field][i][subfield] + else: + del request_init["admin_access_binding"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = marketingplatform_admin.SetPropertyServiceLevelResponse() + return_value = resources.AdminAccessBinding( + name="name_value", + organization_roles=[resources.OrganizationRole.ORG_ADMIN_ROLE], + user_email="user_email_value", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 # Convert return value to protobuf type - return_value = marketingplatform_admin.SetPropertyServiceLevelResponse.pb( - return_value - ) + return_value = resources.AdminAccessBinding.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.set_property_service_level(request) + response = client.update_admin_access_binding(request) # Establish that the response is the type that we expect. - assert isinstance(response, marketingplatform_admin.SetPropertyServiceLevelResponse) + assert isinstance(response, resources.AdminAccessBinding) + assert response.name == "name_value" + assert response.organization_roles == [resources.OrganizationRole.ORG_ADMIN_ROLE] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_property_service_level_rest_interceptors(null_interceptor): +def test_update_admin_access_binding_rest_interceptors(null_interceptor): transport = transports.MarketingplatformAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6910,22 +18254,22 @@ def test_set_property_service_level_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.MarketingplatformAdminServiceRestInterceptor, - "post_set_property_service_level", + "post_update_admin_access_binding", ) as post, mock.patch.object( transports.MarketingplatformAdminServiceRestInterceptor, - "post_set_property_service_level_with_metadata", + "post_update_admin_access_binding_with_metadata", ) as post_with_metadata, mock.patch.object( transports.MarketingplatformAdminServiceRestInterceptor, - "pre_set_property_service_level", + "pre_update_admin_access_binding", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = marketingplatform_admin.SetPropertyServiceLevelRequest.pb( - marketingplatform_admin.SetPropertyServiceLevelRequest() + pb_message = marketingplatform_admin.UpdateAdminAccessBindingRequest.pb( + marketingplatform_admin.UpdateAdminAccessBindingRequest() ) transcode.return_value = { "method": "post", @@ -6937,24 +18281,21 @@ def test_set_property_service_level_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = marketingplatform_admin.SetPropertyServiceLevelResponse.to_json( - marketingplatform_admin.SetPropertyServiceLevelResponse() + return_value = resources.AdminAccessBinding.to_json( + resources.AdminAccessBinding() ) req.return_value.content = return_value - request = marketingplatform_admin.SetPropertyServiceLevelRequest() + request = marketingplatform_admin.UpdateAdminAccessBindingRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = marketingplatform_admin.SetPropertyServiceLevelResponse() - post_with_metadata.return_value = ( - marketingplatform_admin.SetPropertyServiceLevelResponse(), - metadata, - ) + post.return_value = resources.AdminAccessBinding() + post_with_metadata.return_value = resources.AdminAccessBinding(), metadata - client.set_property_service_level( + client.update_admin_access_binding( request, metadata=[ ("key", "val"), @@ -6967,172 +18308,325 @@ def test_set_property_service_level_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_report_property_usage_rest_bad_request( - request_type=marketingplatform_admin.ReportPropertyUsageRequest, -): +def test_initialize_client_w_rest(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding - request_init = {"organization": "organizations/sample1"} - request = request_type(**request_init) + assert client is not None - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.report_property_usage(request) + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_organization_empty_call_rest(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_organization), "__call__") as call: + client.get_organization(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.GetOrganizationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_organizations_empty_call_rest(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_organizations), "__call__" + ) as call: + client.list_organizations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.ListOrganizationsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_find_sales_partner_managed_clients_empty_call_rest(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.find_sales_partner_managed_clients), "__call__" + ) as call: + client.find_sales_partner_managed_clients(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.FindSalesPartnerManagedClientsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_analytics_account_links_empty_call_rest(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_analytics_account_links), "__call__" + ) as call: + client.list_analytics_account_links(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.ListAnalyticsAccountLinksRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_analytics_account_link_empty_call_rest(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_analytics_account_link), "__call__" + ) as call: + client.create_analytics_account_link(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.CreateAnalyticsAccountLinkRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_analytics_account_link_empty_call_rest(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_analytics_account_link), "__call__" + ) as call: + client.delete_analytics_account_link(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.DeleteAnalyticsAccountLinkRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_property_service_level_empty_call_rest(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_property_service_level), "__call__" + ) as call: + client.set_property_service_level(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.SetPropertyServiceLevelRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_report_property_usage_empty_call_rest(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.report_property_usage), "__call__" + ) as call: + client.report_property_usage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.ReportPropertyUsageRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_user_group_empty_call_rest(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_user_group), "__call__") as call: + client.get_user_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.GetUserGroupRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "request_type", - [ - marketingplatform_admin.ReportPropertyUsageRequest, - dict, - ], -) -def test_report_property_usage_rest_call_success(request_type): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_user_groups_empty_call_rest(): client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"organization": "organizations/sample1"} - request = request_type(**request_init) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_user_groups), "__call__") as call: + client.list_user_groups(request=None) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = marketingplatform_admin.ReportPropertyUsageResponse() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.ListUserGroupsRequest() + assert args[0] == request_msg - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = marketingplatform_admin.ReportPropertyUsageResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.report_property_usage(request) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_user_group_empty_call_rest(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Establish that the response is the type that we expect. - assert isinstance(response, marketingplatform_admin.ReportPropertyUsageResponse) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user_group), "__call__" + ) as call: + client.create_user_group(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.CreateUserGroupRequest() + assert args[0] == request_msg -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_report_property_usage_rest_interceptors(null_interceptor): - transport = transports.MarketingplatformAdminServiceRestTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_user_group_empty_call_rest(): + client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.MarketingplatformAdminServiceRestInterceptor(), + transport="rest", ) - client = MarketingplatformAdminServiceClient(transport=transport) - with ( - mock.patch.object(type(client.transport._session), "request") as req, - mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object( - transports.MarketingplatformAdminServiceRestInterceptor, - "post_report_property_usage", - ) as post, - mock.patch.object( - transports.MarketingplatformAdminServiceRestInterceptor, - "post_report_property_usage_with_metadata", - ) as post_with_metadata, - mock.patch.object( - transports.MarketingplatformAdminServiceRestInterceptor, - "pre_report_property_usage", - ) as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = marketingplatform_admin.ReportPropertyUsageRequest.pb( - marketingplatform_admin.ReportPropertyUsageRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user_group), "__call__" + ) as call: + client.update_user_group(request=None) - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = marketingplatform_admin.ReportPropertyUsageResponse.to_json( - marketingplatform_admin.ReportPropertyUsageResponse() - ) - req.return_value.content = return_value + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.UpdateUserGroupRequest() + assert args[0] == request_msg - request = marketingplatform_admin.ReportPropertyUsageRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = marketingplatform_admin.ReportPropertyUsageResponse() - post_with_metadata.return_value = ( - marketingplatform_admin.ReportPropertyUsageResponse(), - metadata, - ) - client.report_property_usage( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_user_group_empty_call_rest(): + client = MarketingplatformAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_group), "__call__" + ) as call: + client.delete_user_group(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.DeleteUserGroupRequest() + assert args[0] == request_msg -def test_initialize_client_w_rest(): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_user_group_member_empty_call_rest(): client = MarketingplatformAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert client is not None + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user_group_member), "__call__" + ) as call: + client.get_user_group_member(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = marketingplatform_admin.GetUserGroupMemberRequest() + assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_get_organization_empty_call_rest(): +def test_list_user_group_members_empty_call_rest(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_organization), "__call__") as call: - client.get_organization(request=None) + with mock.patch.object( + type(client.transport.list_user_group_members), "__call__" + ) as call: + client.list_user_group_members(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.GetOrganizationRequest() + request_msg = marketingplatform_admin.ListUserGroupMembersRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_list_organizations_empty_call_rest(): +def test_create_user_group_member_empty_call_rest(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7140,20 +18634,20 @@ def test_list_organizations_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_organizations), "__call__" + type(client.transport.create_user_group_member), "__call__" ) as call: - client.list_organizations(request=None) + client.create_user_group_member(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.ListOrganizationsRequest() + request_msg = marketingplatform_admin.CreateUserGroupMemberRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_find_sales_partner_managed_clients_empty_call_rest(): +def test_update_user_group_member_empty_call_rest(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7161,20 +18655,20 @@ def test_find_sales_partner_managed_clients_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.find_sales_partner_managed_clients), "__call__" + type(client.transport.update_user_group_member), "__call__" ) as call: - client.find_sales_partner_managed_clients(request=None) + client.update_user_group_member(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.FindSalesPartnerManagedClientsRequest() + request_msg = marketingplatform_admin.UpdateUserGroupMemberRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_list_analytics_account_links_empty_call_rest(): +def test_delete_user_group_member_empty_call_rest(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7182,20 +18676,20 @@ def test_list_analytics_account_links_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_analytics_account_links), "__call__" + type(client.transport.delete_user_group_member), "__call__" ) as call: - client.list_analytics_account_links(request=None) + client.delete_user_group_member(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.ListAnalyticsAccountLinksRequest() + request_msg = marketingplatform_admin.DeleteUserGroupMemberRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_create_analytics_account_link_empty_call_rest(): +def test_get_admin_access_binding_empty_call_rest(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7203,20 +18697,20 @@ def test_create_analytics_account_link_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_analytics_account_link), "__call__" + type(client.transport.get_admin_access_binding), "__call__" ) as call: - client.create_analytics_account_link(request=None) + client.get_admin_access_binding(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.CreateAnalyticsAccountLinkRequest() + request_msg = marketingplatform_admin.GetAdminAccessBindingRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_delete_analytics_account_link_empty_call_rest(): +def test_list_admin_access_bindings_empty_call_rest(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7224,20 +18718,20 @@ def test_delete_analytics_account_link_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_analytics_account_link), "__call__" + type(client.transport.list_admin_access_bindings), "__call__" ) as call: - client.delete_analytics_account_link(request=None) + client.list_admin_access_bindings(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.DeleteAnalyticsAccountLinkRequest() + request_msg = marketingplatform_admin.ListAdminAccessBindingsRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_set_property_service_level_empty_call_rest(): +def test_create_admin_access_binding_empty_call_rest(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7245,20 +18739,20 @@ def test_set_property_service_level_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.set_property_service_level), "__call__" + type(client.transport.create_admin_access_binding), "__call__" ) as call: - client.set_property_service_level(request=None) + client.create_admin_access_binding(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.SetPropertyServiceLevelRequest() + request_msg = marketingplatform_admin.CreateAdminAccessBindingRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_report_property_usage_empty_call_rest(): +def test_update_admin_access_binding_empty_call_rest(): client = MarketingplatformAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7266,14 +18760,14 @@ def test_report_property_usage_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.report_property_usage), "__call__" + type(client.transport.update_admin_access_binding), "__call__" ) as call: - client.report_property_usage(request=None) + client.update_admin_access_binding(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = marketingplatform_admin.ReportPropertyUsageRequest() + request_msg = marketingplatform_admin.UpdateAdminAccessBindingRequest() assert args[0] == request_msg @@ -7318,6 +18812,20 @@ def test_marketingplatform_admin_service_base_transport(): "delete_analytics_account_link", "set_property_service_level", "report_property_usage", + "get_user_group", + "list_user_groups", + "create_user_group", + "update_user_group", + "delete_user_group", + "get_user_group_member", + "list_user_group_members", + "create_user_group_member", + "update_user_group_member", + "delete_user_group_member", + "get_admin_access_binding", + "list_admin_access_bindings", + "create_admin_access_binding", + "update_admin_access_binding", ) for method in methods: with pytest.raises(NotImplementedError): @@ -7630,6 +19138,48 @@ def test_marketingplatform_admin_service_client_transport_session_collision( session1 = client1.transport.report_property_usage._session session2 = client2.transport.report_property_usage._session assert session1 != session2 + session1 = client1.transport.get_user_group._session + session2 = client2.transport.get_user_group._session + assert session1 != session2 + session1 = client1.transport.list_user_groups._session + session2 = client2.transport.list_user_groups._session + assert session1 != session2 + session1 = client1.transport.create_user_group._session + session2 = client2.transport.create_user_group._session + assert session1 != session2 + session1 = client1.transport.update_user_group._session + session2 = client2.transport.update_user_group._session + assert session1 != session2 + session1 = client1.transport.delete_user_group._session + session2 = client2.transport.delete_user_group._session + assert session1 != session2 + session1 = client1.transport.get_user_group_member._session + session2 = client2.transport.get_user_group_member._session + assert session1 != session2 + session1 = client1.transport.list_user_group_members._session + session2 = client2.transport.list_user_group_members._session + assert session1 != session2 + session1 = client1.transport.create_user_group_member._session + session2 = client2.transport.create_user_group_member._session + assert session1 != session2 + session1 = client1.transport.update_user_group_member._session + session2 = client2.transport.update_user_group_member._session + assert session1 != session2 + session1 = client1.transport.delete_user_group_member._session + session2 = client2.transport.delete_user_group_member._session + assert session1 != session2 + session1 = client1.transport.get_admin_access_binding._session + session2 = client2.transport.get_admin_access_binding._session + assert session1 != session2 + session1 = client1.transport.list_admin_access_bindings._session + session2 = client2.transport.list_admin_access_bindings._session + assert session1 != session2 + session1 = client1.transport.create_admin_access_binding._session + session2 = client2.transport.create_admin_access_binding._session + assert session1 != session2 + session1 = client1.transport.update_admin_access_binding._session + session2 = client2.transport.update_admin_access_binding._session + assert session1 != session2 def test_marketingplatform_admin_service_grpc_transport_channel(): @@ -7781,9 +19331,34 @@ def test_parse_account_path(): assert expected == actual -def test_analytics_account_link_path(): +def test_admin_access_binding_path(): organization = "whelk" - analytics_account_link = "octopus" + admin_access_binding = "octopus" + expected = "organizations/{organization}/adminAccessBindings/{admin_access_binding}".format( + organization=organization, + admin_access_binding=admin_access_binding, + ) + actual = MarketingplatformAdminServiceClient.admin_access_binding_path( + organization, admin_access_binding + ) + assert expected == actual + + +def test_parse_admin_access_binding_path(): + expected = { + "organization": "oyster", + "admin_access_binding": "nudibranch", + } + path = MarketingplatformAdminServiceClient.admin_access_binding_path(**expected) + + # Check that the path construction is reversible. + actual = MarketingplatformAdminServiceClient.parse_admin_access_binding_path(path) + assert expected == actual + + +def test_analytics_account_link_path(): + organization = "cuttlefish" + analytics_account_link = "mussel" expected = "organizations/{organization}/analyticsAccountLinks/{analytics_account_link}".format( organization=organization, analytics_account_link=analytics_account_link, @@ -7796,8 +19371,8 @@ def test_analytics_account_link_path(): def test_parse_analytics_account_link_path(): expected = { - "organization": "oyster", - "analytics_account_link": "nudibranch", + "organization": "winkle", + "analytics_account_link": "nautilus", } path = MarketingplatformAdminServiceClient.analytics_account_link_path(**expected) @@ -7807,7 +19382,7 @@ def test_parse_analytics_account_link_path(): def test_organization_path(): - organization = "cuttlefish" + organization = "scallop" expected = "organizations/{organization}".format( organization=organization, ) @@ -7817,7 +19392,7 @@ def test_organization_path(): def test_parse_organization_path(): expected = { - "organization": "mussel", + "organization": "abalone", } path = MarketingplatformAdminServiceClient.organization_path(**expected) @@ -7827,7 +19402,7 @@ def test_parse_organization_path(): def test_property_path(): - property = "winkle" + property = "squid" expected = "properties/{property}".format( property=property, ) @@ -7837,7 +19412,7 @@ def test_property_path(): def test_parse_property_path(): expected = { - "property": "nautilus", + "property": "clam", } path = MarketingplatformAdminServiceClient.property_path(**expected) @@ -7846,8 +19421,63 @@ def test_parse_property_path(): assert expected == actual +def test_user_group_path(): + organization = "whelk" + user_group = "octopus" + expected = "organizations/{organization}/userGroups/{user_group}".format( + organization=organization, + user_group=user_group, + ) + actual = MarketingplatformAdminServiceClient.user_group_path( + organization, user_group + ) + assert expected == actual + + +def test_parse_user_group_path(): + expected = { + "organization": "oyster", + "user_group": "nudibranch", + } + path = MarketingplatformAdminServiceClient.user_group_path(**expected) + + # Check that the path construction is reversible. + actual = MarketingplatformAdminServiceClient.parse_user_group_path(path) + assert expected == actual + + +def test_user_group_member_path(): + organization = "cuttlefish" + user_group = "mussel" + member = "winkle" + expected = ( + "organizations/{organization}/userGroups/{user_group}/members/{member}".format( + organization=organization, + user_group=user_group, + member=member, + ) + ) + actual = MarketingplatformAdminServiceClient.user_group_member_path( + organization, user_group, member + ) + assert expected == actual + + +def test_parse_user_group_member_path(): + expected = { + "organization": "nautilus", + "user_group": "scallop", + "member": "abalone", + } + path = MarketingplatformAdminServiceClient.user_group_member_path(**expected) + + # Check that the path construction is reversible. + actual = MarketingplatformAdminServiceClient.parse_user_group_member_path(path) + assert expected == actual + + def test_common_billing_account_path(): - billing_account = "scallop" + billing_account = "squid" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -7859,7 +19489,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "abalone", + "billing_account": "clam", } path = MarketingplatformAdminServiceClient.common_billing_account_path(**expected) @@ -7869,7 +19499,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "squid" + folder = "whelk" expected = "folders/{folder}".format( folder=folder, ) @@ -7879,7 +19509,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "clam", + "folder": "octopus", } path = MarketingplatformAdminServiceClient.common_folder_path(**expected) @@ -7889,7 +19519,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "whelk" + organization = "oyster" expected = "organizations/{organization}".format( organization=organization, ) @@ -7899,7 +19529,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "octopus", + "organization": "nudibranch", } path = MarketingplatformAdminServiceClient.common_organization_path(**expected) @@ -7909,7 +19539,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "oyster" + project = "cuttlefish" expected = "projects/{project}".format( project=project, ) @@ -7919,7 +19549,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nudibranch", + "project": "mussel", } path = MarketingplatformAdminServiceClient.common_project_path(**expected) @@ -7929,8 +19559,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "cuttlefish" - location = "mussel" + project = "winkle" + location = "nautilus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -7941,8 +19571,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "winkle", - "location": "nautilus", + "project": "scallop", + "location": "abalone", } path = MarketingplatformAdminServiceClient.common_location_path(**expected) diff --git a/packages/google-analytics-data/google/analytics/data_v1alpha/__init__.py b/packages/google-analytics-data/google/analytics/data_v1alpha/__init__.py index 75ab86327bd5..ea125eb72d4f 100644 --- a/packages/google-analytics-data/google/analytics/data_v1alpha/__init__.py +++ b/packages/google-analytics-data/google/analytics/data_v1alpha/__init__.py @@ -42,6 +42,8 @@ AudienceList, AudienceListMetadata, AudienceRow, + ChatRequest, + ChatResponse, CreateAudienceListRequest, CreateRecurringAudienceListRequest, CreateReportTaskRequest, @@ -120,8 +122,10 @@ NumericFilter, NumericValue, OrderBy, + PropertyChatQuota, PropertyQuota, QuotaStatus, + ResponseBlock, ResponseMetaData, RestrictedMetricType, Row, @@ -164,6 +168,8 @@ "AudienceListMetadata", "AudienceRow", "BetweenFilter", + "ChatRequest", + "ChatResponse", "Cohort", "CohortReportSettings", "CohortSpec", @@ -226,6 +232,7 @@ "NumericFilter", "NumericValue", "OrderBy", + "PropertyChatQuota", "PropertyQuota", "PropertyQuotasSnapshot", "QueryAudienceListRequest", @@ -236,6 +243,7 @@ "RecurringAudienceList", "ReportTask", "ReportTaskMetadata", + "ResponseBlock", "ResponseMetaData", "RestrictedMetricType", "Row", diff --git a/packages/google-analytics-data/google/analytics/data_v1alpha/gapic_metadata.json b/packages/google-analytics-data/google/analytics/data_v1alpha/gapic_metadata.json index 5789ccfbbdd6..ebc8adefc637 100644 --- a/packages/google-analytics-data/google/analytics/data_v1alpha/gapic_metadata.json +++ b/packages/google-analytics-data/google/analytics/data_v1alpha/gapic_metadata.json @@ -10,6 +10,11 @@ "grpc": { "libraryClient": "AlphaAnalyticsDataClient", "rpcs": { + "Chat": { + "methods": [ + "chat" + ] + }, "CreateAudienceList": { "methods": [ "create_audience_list" @@ -90,6 +95,11 @@ "grpc-async": { "libraryClient": "AlphaAnalyticsDataAsyncClient", "rpcs": { + "Chat": { + "methods": [ + "chat" + ] + }, "CreateAudienceList": { "methods": [ "create_audience_list" @@ -170,6 +180,11 @@ "rest": { "libraryClient": "AlphaAnalyticsDataClient", "rpcs": { + "Chat": { + "methods": [ + "chat" + ] + }, "CreateAudienceList": { "methods": [ "create_audience_list" diff --git a/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/async_client.py b/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/async_client.py index 4831ba9162f2..576076a975e7 100644 --- a/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/async_client.py +++ b/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/async_client.py @@ -84,6 +84,8 @@ class AlphaAnalyticsDataAsyncClient: ) metadata_path = staticmethod(AlphaAnalyticsDataClient.metadata_path) parse_metadata_path = staticmethod(AlphaAnalyticsDataClient.parse_metadata_path) + property_path = staticmethod(AlphaAnalyticsDataClient.property_path) + parse_property_path = staticmethod(AlphaAnalyticsDataClient.parse_property_path) property_quotas_snapshot_path = staticmethod( AlphaAnalyticsDataClient.property_quotas_snapshot_path ) @@ -2047,6 +2049,98 @@ async def sample_list_report_tasks(): # Done; return the response. return response + async def chat( + self, + request: Optional[Union[analytics_data_api.ChatRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> analytics_data_api.ChatResponse: + r"""Provides a chat interface for interacting with Google Analytics + data through the API. + + This product uses AI and may display inaccurate info. Your chat + activity may be used to improve the product and your use is + subject to Google's + `Terms `__, `AI Use + Policy `__, + and `Privacy Policy `__. + `Learn more about Chat AI + Privacy `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import data_v1alpha + + async def sample_chat(): + # Create a client + client = data_v1alpha.AlphaAnalyticsDataAsyncClient() + + # Initialize request argument(s) + request = data_v1alpha.ChatRequest( + property="property_value", + user_query="user_query_value", + ) + + # Make the request + response = await client.chat(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.data_v1alpha.types.ChatRequest, dict]]): + The request object. Request message for the Chat method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.analytics.data_v1alpha.types.ChatResponse: + Response message for the Chat method. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_data_api.ChatRequest): + request = analytics_data_api.ChatRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.chat] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("property", request.property),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def run_report( self, request: Optional[Union[analytics_data_api.RunReportRequest, dict]] = None, diff --git a/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py b/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py index e119565d7950..68e831d29f5b 100644 --- a/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py +++ b/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/client.py @@ -208,6 +208,21 @@ def parse_metadata_path(path: str) -> Dict[str, str]: m = re.match(r"^properties/(?P.+?)/metadata$", path) return m.groupdict() if m else {} + @staticmethod + def property_path( + property: str, + ) -> str: + """Returns a fully-qualified property string.""" + return "properties/{property}".format( + property=property, + ) + + @staticmethod + def parse_property_path(path: str) -> Dict[str, str]: + """Parses a property path into its component segments.""" + m = re.match(r"^properties/(?P.+?)$", path) + return m.groupdict() if m else {} + @staticmethod def property_quotas_snapshot_path( property: str, @@ -2359,6 +2374,98 @@ def sample_list_report_tasks(): # Done; return the response. return response + def chat( + self, + request: Optional[Union[analytics_data_api.ChatRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> analytics_data_api.ChatResponse: + r"""Provides a chat interface for interacting with Google Analytics + data through the API. + + This product uses AI and may display inaccurate info. Your chat + activity may be used to improve the product and your use is + subject to Google's + `Terms `__, `AI Use + Policy `__, + and `Privacy Policy `__. + `Learn more about Chat AI + Privacy `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import data_v1alpha + + def sample_chat(): + # Create a client + client = data_v1alpha.AlphaAnalyticsDataClient() + + # Initialize request argument(s) + request = data_v1alpha.ChatRequest( + property="property_value", + user_query="user_query_value", + ) + + # Make the request + response = client.chat(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.data_v1alpha.types.ChatRequest, dict]): + The request object. Request message for the Chat method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.analytics.data_v1alpha.types.ChatResponse: + Response message for the Chat method. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_data_api.ChatRequest): + request = analytics_data_api.ChatRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.chat] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("property", request.property),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def run_report( self, request: Optional[Union[analytics_data_api.RunReportRequest, dict]] = None, diff --git a/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/base.py b/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/base.py index 6b3e2158a505..fa2955d07138 100644 --- a/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/base.py +++ b/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/base.py @@ -40,6 +40,7 @@ class AlphaAnalyticsDataTransport(abc.ABC): AUTH_SCOPES = ( "https://www.googleapis.com/auth/analytics", + "https://www.googleapis.com/auth/analytics.chatbot.read", "https://www.googleapis.com/auth/analytics.readonly", ) @@ -209,6 +210,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.chat: gapic_v1.method.wrap_method( + self.chat, + default_timeout=None, + client_info=client_info, + ), self.run_report: gapic_v1.method.wrap_method( self.run_report, default_timeout=None, @@ -381,6 +387,17 @@ def list_report_tasks( ]: raise NotImplementedError() + @property + def chat( + self, + ) -> Callable[ + [analytics_data_api.ChatRequest], + Union[ + analytics_data_api.ChatResponse, Awaitable[analytics_data_api.ChatResponse] + ], + ]: + raise NotImplementedError() + @property def run_report( self, diff --git a/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc.py b/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc.py index ffc3aee9950e..2054b3ea35f6 100644 --- a/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc.py +++ b/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc.py @@ -869,6 +869,42 @@ def list_report_tasks( ) return self._stubs["list_report_tasks"] + @property + def chat( + self, + ) -> Callable[[analytics_data_api.ChatRequest], analytics_data_api.ChatResponse]: + r"""Return a callable for the chat method over gRPC. + + Provides a chat interface for interacting with Google Analytics + data through the API. + + This product uses AI and may display inaccurate info. Your chat + activity may be used to improve the product and your use is + subject to Google's + `Terms `__, `AI Use + Policy `__, + and `Privacy Policy `__. + `Learn more about Chat AI + Privacy `__. + + Returns: + Callable[[~.ChatRequest], + ~.ChatResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "chat" not in self._stubs: + self._stubs["chat"] = self._logged_channel.unary_unary( + "/google.analytics.data.v1alpha.AlphaAnalyticsData/Chat", + request_serializer=analytics_data_api.ChatRequest.serialize, + response_deserializer=analytics_data_api.ChatResponse.deserialize, + ) + return self._stubs["chat"] + @property def run_report( self, diff --git a/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py b/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py index 1840922b5f7f..a7e8968f8022 100644 --- a/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py +++ b/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py @@ -881,6 +881,44 @@ def list_report_tasks( ) return self._stubs["list_report_tasks"] + @property + def chat( + self, + ) -> Callable[ + [analytics_data_api.ChatRequest], Awaitable[analytics_data_api.ChatResponse] + ]: + r"""Return a callable for the chat method over gRPC. + + Provides a chat interface for interacting with Google Analytics + data through the API. + + This product uses AI and may display inaccurate info. Your chat + activity may be used to improve the product and your use is + subject to Google's + `Terms `__, `AI Use + Policy `__, + and `Privacy Policy `__. + `Learn more about Chat AI + Privacy `__. + + Returns: + Callable[[~.ChatRequest], + Awaitable[~.ChatResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "chat" not in self._stubs: + self._stubs["chat"] = self._logged_channel.unary_unary( + "/google.analytics.data.v1alpha.AlphaAnalyticsData/Chat", + request_serializer=analytics_data_api.ChatRequest.serialize, + response_deserializer=analytics_data_api.ChatResponse.deserialize, + ) + return self._stubs["chat"] + @property def run_report( self, @@ -1024,6 +1062,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.chat: self._wrap_method( + self.chat, + default_timeout=None, + client_info=client_info, + ), self.run_report: self._wrap_method( self.run_report, default_timeout=None, diff --git a/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest.py b/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest.py index 507738e1324e..4a8b9ae3596d 100644 --- a/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest.py +++ b/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest.py @@ -73,6 +73,14 @@ class AlphaAnalyticsDataRestInterceptor: .. code-block:: python class MyCustomAlphaAnalyticsDataInterceptor(AlphaAnalyticsDataRestInterceptor): + def pre_chat(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_chat(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_audience_list(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -199,6 +207,54 @@ def post_run_report(self, response): """ + def pre_chat( + self, + request: analytics_data_api.ChatRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[analytics_data_api.ChatRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for chat + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlphaAnalyticsData server. + """ + return request, metadata + + def post_chat( + self, response: analytics_data_api.ChatResponse + ) -> analytics_data_api.ChatResponse: + """Post-rpc interceptor for chat + + DEPRECATED. Please use the `post_chat_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AlphaAnalyticsData server but before + it is returned to user code. This `post_chat` interceptor runs + before the `post_chat_with_metadata` interceptor. + """ + return response + + def post_chat_with_metadata( + self, + response: analytics_data_api.ChatResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + analytics_data_api.ChatResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for chat + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AlphaAnalyticsData server but before it is returned to user code. + + We recommend only using this `post_chat_with_metadata` + interceptor in new development instead of the `post_chat` interceptor. + When both interceptors are used, this `post_chat_with_metadata` interceptor runs after the + `post_chat` interceptor. The (possibly modified) response returned by + `post_chat` will be passed to + `post_chat_with_metadata`. + """ + return response, metadata + def pre_create_audience_list( self, request: analytics_data_api.CreateAudienceListRequest, @@ -1084,6 +1140,151 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client + class _Chat( + _BaseAlphaAnalyticsDataRestTransport._BaseChat, AlphaAnalyticsDataRestStub + ): + def __hash__(self): + return hash("AlphaAnalyticsDataRestTransport.Chat") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: analytics_data_api.ChatRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> analytics_data_api.ChatResponse: + r"""Call the chat method over HTTP. + + Args: + request (~.analytics_data_api.ChatRequest): + The request object. Request message for the Chat method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.analytics_data_api.ChatResponse: + Response message for the Chat method. + """ + + http_options = ( + _BaseAlphaAnalyticsDataRestTransport._BaseChat._get_http_options() + ) + request, metadata = self._interceptor.pre_chat(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAlphaAnalyticsDataRestTransport._BaseChat, + "_BaseChat__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.analytics.data_v1alpha.AlphaAnalyticsDataClient.Chat", + extra={ + "serviceName": "google.analytics.data.v1alpha.AlphaAnalyticsData", + "rpcName": "Chat", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AlphaAnalyticsDataRestTransport._Chat._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = analytics_data_api.ChatResponse() + pb_resp = analytics_data_api.ChatResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_chat(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_chat_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = analytics_data_api.ChatResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.analytics.data_v1alpha.AlphaAnalyticsDataClient.chat", + extra={ + "serviceName": "google.analytics.data.v1alpha.AlphaAnalyticsData", + "rpcName": "Chat", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _CreateAudienceList( _BaseAlphaAnalyticsDataRestTransport._BaseCreateAudienceList, AlphaAnalyticsDataRestStub, @@ -3371,6 +3572,14 @@ def __call__( ) return resp + @property + def chat( + self, + ) -> Callable[[analytics_data_api.ChatRequest], analytics_data_api.ChatResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Chat(self._session, self._host, self._interceptor) # type: ignore + @property def create_audience_list( self, diff --git a/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest_base.py b/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest_base.py index 98268e0c11a6..e17aacad19f1 100644 --- a/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest_base.py +++ b/packages/google-analytics-data/google/analytics/data_v1alpha/services/alpha_analytics_data/transports/rest_base.py @@ -88,6 +88,23 @@ def __init__( api_audience=api_audience, ) + class _BaseChat: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{property=properties/*}:chat", + "body": "*", + }, + ] + return http_options + class _BaseCreateAudienceList: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-analytics-data/google/analytics/data_v1alpha/types/__init__.py b/packages/google-analytics-data/google/analytics/data_v1alpha/types/__init__.py index 441a945ab890..5529e0737e0a 100644 --- a/packages/google-analytics-data/google/analytics/data_v1alpha/types/__init__.py +++ b/packages/google-analytics-data/google/analytics/data_v1alpha/types/__init__.py @@ -19,6 +19,8 @@ AudienceList, AudienceListMetadata, AudienceRow, + ChatRequest, + ChatResponse, CreateAudienceListRequest, CreateRecurringAudienceListRequest, CreateReportTaskRequest, @@ -97,8 +99,10 @@ NumericFilter, NumericValue, OrderBy, + PropertyChatQuota, PropertyQuota, QuotaStatus, + ResponseBlock, ResponseMetaData, RestrictedMetricType, Row, @@ -138,6 +142,8 @@ "AudienceList", "AudienceListMetadata", "AudienceRow", + "ChatRequest", + "ChatResponse", "CreateAudienceListRequest", "CreateRecurringAudienceListRequest", "CreateReportTaskRequest", @@ -210,8 +216,10 @@ "NumericFilter", "NumericValue", "OrderBy", + "PropertyChatQuota", "PropertyQuota", "QuotaStatus", + "ResponseBlock", "ResponseMetaData", "Row", "SamplingMetadata", diff --git a/packages/google-analytics-data/google/analytics/data_v1alpha/types/analytics_data_api.py b/packages/google-analytics-data/google/analytics/data_v1alpha/types/analytics_data_api.py index f456e2f498f0..db67840df91b 100644 --- a/packages/google-analytics-data/google/analytics/data_v1alpha/types/analytics_data_api.py +++ b/packages/google-analytics-data/google/analytics/data_v1alpha/types/analytics_data_api.py @@ -54,6 +54,8 @@ "GetReportTaskRequest", "ListReportTasksRequest", "ListReportTasksResponse", + "ChatRequest", + "ChatResponse", "RunReportRequest", "RunReportResponse", "GetMetadataRequest", @@ -1615,6 +1617,83 @@ def raw_page(self): ) +class ChatRequest(proto.Message): + r"""Request message for the Chat method. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + property (str): + Required. The property to chat about. + Format: properties/{property} + user_query (str): + Required. The user's query. + session_id (str): + Optional. Provide this session ID to continue + an existing conversation and maintain context. + If this field is empty or unset, a new chat + session is created. Invalid session IDs will + result in an error. + + This field is a member of `oneof`_ ``_session_id``. + return_property_quota (bool): + Optional. If true, the response will include the current + state of this Analytics Property's quota. Quota is returned + in `PropertyChatQuota <#PropertyChatQuota>`__. + """ + + property: str = proto.Field( + proto.STRING, + number=1, + ) + user_query: str = proto.Field( + proto.STRING, + number=2, + ) + session_id: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + return_property_quota: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ChatResponse(proto.Message): + r"""Response message for the Chat method. + + Attributes: + session_id (str): + The unique identifier for this chat session. + Provide this ID in subsequent requests to + maintain conversational context. + blocks (MutableSequence[google.analytics.data_v1alpha.types.ResponseBlock]): + The response blocks that make up the chat + response. This can include text, tables, and + lists. + property_quota (google.analytics.data_v1alpha.types.PropertyChatQuota): + This Analytics Property's quota state + including this request. + """ + + session_id: str = proto.Field( + proto.STRING, + number=1, + ) + blocks: MutableSequence[data.ResponseBlock] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=data.ResponseBlock, + ) + property_quota: data.PropertyChatQuota = proto.Field( + proto.MESSAGE, + number=3, + message=data.PropertyChatQuota, + ) + + class RunReportRequest(proto.Message): r"""The request to generate a report. diff --git a/packages/google-analytics-data/google/analytics/data_v1alpha/types/data.py b/packages/google-analytics-data/google/analytics/data_v1alpha/types/data.py index 78501126c690..6526d51e6993 100644 --- a/packages/google-analytics-data/google/analytics/data_v1alpha/types/data.py +++ b/packages/google-analytics-data/google/analytics/data_v1alpha/types/data.py @@ -66,6 +66,7 @@ "Funnel", "FunnelStep", "FunnelSubReport", + "ResponseBlock", "UserSegment", "UserSegmentCriteria", "UserSegmentConditionGroup", @@ -104,6 +105,7 @@ "MetricMetadata", "ComparisonMetadata", "ConversionMetadata", + "PropertyChatQuota", }, ) @@ -1399,6 +1401,9 @@ class ResponseMetaData(proto.Message): be defined. section (google.analytics.data_v1alpha.types.Section): Identifies the type of data in the report. + data_truncation_reasons (MutableSequence[google.analytics.data_v1alpha.types.ResponseMetaData.DataTruncationReason]): + If set, indicate there is data truncation in + the report. """ class SchemaRestrictionResponse(proto.Message): @@ -1450,6 +1455,134 @@ class ActiveMetricRestriction(proto.Message): message="ResponseMetaData.SchemaRestrictionResponse.ActiveMetricRestriction", ) + class DataTruncationReason(proto.Message): + r"""Describes a reason for data truncation in the report. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + data_truncation_type (google.analytics.data_v1alpha.types.ResponseMetaData.DataTruncationReason.DataTruncationType): + The type of data truncation. + + This field is a member of `oneof`_ ``_data_truncation_type``. + data_truncation_message (str): + A descriptive message explaining the data + truncation. + + This field is a member of `oneof`_ ``_data_truncation_message``. + data_truncation_date (str): + The data truncation date in the format + YYYY-MM-DD. Indicates data before this date is + truncated. + + This field is a member of `oneof`_ ``_data_truncation_date``. + data_truncation_date_ranges (MutableSequence[google.analytics.data_v1alpha.types.ResponseMetaData.DataTruncationReason.DataTruncationDateRange]): + The truncated date ranges. + """ + + class DataTruncationType(proto.Enum): + r"""The type of data truncation. + + Values: + DATA_TRUNCATION_TYPE_UNSPECIFIED (0): + Unspecified type. + DATA_TRUNCATION_TYPE_RULES_BASED_MODELS (1): + Data is truncated in attribution report for + rules-based models golden date. + DATA_TRUNCATION_TYPE_DATA_DRIVEN_ATTRIBUTION (2): + Data is truncated in attribution report for + data driven attribution golden date. + DATA_TRUNCATION_TYPE_DV360 (3): + Data is truncated because DV360 policy does + not permit data older than 2 years from being + returned. + DATA_TRUNCATION_TYPE_CM360 (4): + Data is truncated because CM360 policy does + not permit data older than 2 years from being + returned. + DATA_TRUNCATION_TYPE_ITEM_SCOPED_ECOMMERCE_METRICS (5): + New item-scoped ecommerce metrics only have + data after a specific date. + DATA_TRUNCATION_TYPE_EVENT_SCOPED_ECOMMERCE_METRICS (6): + New event-scoped ecommerce metrics only have + data after a specific date. + DATA_TRUNCATION_TYPE_DATE_RANGE (7): + Query date range may not be fully served. + DATA_TRUNCATION_TYPE_PROPERTY (8): + Data truncated because the query attempts to + read event data prior to its retention date. + DATA_TRUNCATION_TYPE_CONVERSIONS (9): + Data is truncated in conversions report. + DATA_TRUNCATION_TYPE_GOOGLE_ADS (10): + Data is truncated due to Google Ads 36 month + retention policy. + """ + + DATA_TRUNCATION_TYPE_UNSPECIFIED = 0 + DATA_TRUNCATION_TYPE_RULES_BASED_MODELS = 1 + DATA_TRUNCATION_TYPE_DATA_DRIVEN_ATTRIBUTION = 2 + DATA_TRUNCATION_TYPE_DV360 = 3 + DATA_TRUNCATION_TYPE_CM360 = 4 + DATA_TRUNCATION_TYPE_ITEM_SCOPED_ECOMMERCE_METRICS = 5 + DATA_TRUNCATION_TYPE_EVENT_SCOPED_ECOMMERCE_METRICS = 6 + DATA_TRUNCATION_TYPE_DATE_RANGE = 7 + DATA_TRUNCATION_TYPE_PROPERTY = 8 + DATA_TRUNCATION_TYPE_CONVERSIONS = 9 + DATA_TRUNCATION_TYPE_GOOGLE_ADS = 10 + + class DataTruncationDateRange(proto.Message): + r"""Define the truncated date range from start_date to end_date. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start_date (str): + The start date in the format YYYY-MM-DD + (inclusive). + + This field is a member of `oneof`_ ``_start_date``. + end_date (str): + The end date in the format YYYY-MM-DD + (inclusive). + + This field is a member of `oneof`_ ``_end_date``. + """ + + start_date: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + end_date: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + + data_truncation_type: "ResponseMetaData.DataTruncationReason.DataTruncationType" = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum="ResponseMetaData.DataTruncationReason.DataTruncationType", + ) + data_truncation_message: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + data_truncation_date: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + data_truncation_date_ranges: MutableSequence[ + "ResponseMetaData.DataTruncationReason.DataTruncationDateRange" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="ResponseMetaData.DataTruncationReason.DataTruncationDateRange", + ) + data_loss_from_other_row: bool = proto.Field( proto.BOOL, number=3, @@ -1490,6 +1623,13 @@ class ActiveMetricRestriction(proto.Message): number=10, enum="Section", ) + data_truncation_reasons: MutableSequence[DataTruncationReason] = ( + proto.RepeatedField( + proto.MESSAGE, + number=11, + message=DataTruncationReason, + ) + ) class DimensionHeader(proto.Message): @@ -1948,6 +2088,110 @@ class FunnelSubReport(proto.Message): ) +class ResponseBlock(proto.Message): + r"""One block of structured data in chat response. + + 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: + text (str): + A block of text. + + This field is a member of `oneof`_ ``block``. + table (google.analytics.data_v1alpha.types.ResponseBlock.DataTable): + A block of table data. + + This field is a member of `oneof`_ ``block``. + """ + + class DataTableCell(proto.Message): + r"""A cell in a data table. + + Attributes: + value (str): + The value of the cell. + """ + + value: str = proto.Field( + proto.STRING, + number=1, + ) + + class DataTableHeader(proto.Message): + r"""Describes a column header in a DataTable. + + Attributes: + header (str): + The header name. + data_type (str): + The data type. + """ + + header: str = proto.Field( + proto.STRING, + number=1, + ) + data_type: str = proto.Field( + proto.STRING, + number=2, + ) + + class DataTableRow(proto.Message): + r"""A row in a DataTable. + + Attributes: + columns (MutableSequence[google.analytics.data_v1alpha.types.ResponseBlock.DataTableCell]): + The cell values in the row. + """ + + columns: MutableSequence["ResponseBlock.DataTableCell"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ResponseBlock.DataTableCell", + ) + + class DataTable(proto.Message): + r"""A table of data. + + Attributes: + headers (MutableSequence[google.analytics.data_v1alpha.types.ResponseBlock.DataTableHeader]): + Describes dimension columns. The number of + headers and ordering of headers matches the + dimensions present in rows. + rows (MutableSequence[google.analytics.data_v1alpha.types.ResponseBlock.DataTableRow]): + Rows of dimension value combinations and + metric values in the report. + """ + + headers: MutableSequence["ResponseBlock.DataTableHeader"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ResponseBlock.DataTableHeader", + ) + rows: MutableSequence["ResponseBlock.DataTableRow"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="ResponseBlock.DataTableRow", + ) + + text: str = proto.Field( + proto.STRING, + number=1, + oneof="block", + ) + table: DataTable = proto.Field( + proto.MESSAGE, + number=2, + oneof="block", + message=DataTable, + ) + + class UserSegment(proto.Message): r"""User segments are subsets of users who engaged with your site or app. For example, users who have previously purchased; users @@ -3631,4 +3875,26 @@ class ConversionMetadata(proto.Message): ) +class PropertyChatQuota(proto.Message): + r"""Property quota for chatbot specific fields. + + Attributes: + tokens_per_day (google.analytics.data_v1alpha.types.QuotaStatus): + Chat tokens consumed per day. + tokens_per_hour (google.analytics.data_v1alpha.types.QuotaStatus): + Chat tokens consumed per hour. + """ + + tokens_per_day: "QuotaStatus" = proto.Field( + proto.MESSAGE, + number=1, + message="QuotaStatus", + ) + tokens_per_hour: "QuotaStatus" = proto.Field( + proto.MESSAGE, + number=2, + message="QuotaStatus", + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-analytics-data/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_chat_async.py b/packages/google-analytics-data/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_chat_async.py new file mode 100644 index 000000000000..762cc852deeb --- /dev/null +++ b/packages/google-analytics-data/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_chat_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Chat +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-data + + +# [START analyticsdata_v1alpha_generated_AlphaAnalyticsData_Chat_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.analytics import data_v1alpha + + +async def sample_chat(): + # Create a client + client = data_v1alpha.AlphaAnalyticsDataAsyncClient() + + # Initialize request argument(s) + request = data_v1alpha.ChatRequest( + property="property_value", + user_query="user_query_value", + ) + + # Make the request + response = await client.chat(request=request) + + # Handle the response + print(response) + + +# [END analyticsdata_v1alpha_generated_AlphaAnalyticsData_Chat_async] diff --git a/packages/google-analytics-data/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_chat_sync.py b/packages/google-analytics-data/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_chat_sync.py new file mode 100644 index 000000000000..5541143dbc73 --- /dev/null +++ b/packages/google-analytics-data/samples/generated_samples/analyticsdata_v1alpha_generated_alpha_analytics_data_chat_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Chat +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-data + + +# [START analyticsdata_v1alpha_generated_AlphaAnalyticsData_Chat_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.analytics import data_v1alpha + + +def sample_chat(): + # Create a client + client = data_v1alpha.AlphaAnalyticsDataClient() + + # Initialize request argument(s) + request = data_v1alpha.ChatRequest( + property="property_value", + user_query="user_query_value", + ) + + # Make the request + response = client.chat(request=request) + + # Handle the response + print(response) + + +# [END analyticsdata_v1alpha_generated_AlphaAnalyticsData_Chat_sync] diff --git a/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json b/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json index 9b97c5021543..f84f55891b3e 100644 --- a/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json +++ b/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json @@ -11,6 +11,159 @@ "version": "0.23.1" }, "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.data_v1alpha.AlphaAnalyticsDataAsyncClient", + "shortName": "AlphaAnalyticsDataAsyncClient" + }, + "fullName": "google.analytics.data_v1alpha.AlphaAnalyticsDataAsyncClient.chat", + "method": { + "fullName": "google.analytics.data.v1alpha.AlphaAnalyticsData.Chat", + "service": { + "fullName": "google.analytics.data.v1alpha.AlphaAnalyticsData", + "shortName": "AlphaAnalyticsData" + }, + "shortName": "Chat" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.data_v1alpha.types.ChatRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.analytics.data_v1alpha.types.ChatResponse", + "shortName": "chat" + }, + "description": "Sample for Chat", + "file": "analyticsdata_v1alpha_generated_alpha_analytics_data_chat_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsdata_v1alpha_generated_AlphaAnalyticsData_Chat_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsdata_v1alpha_generated_alpha_analytics_data_chat_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.data_v1alpha.AlphaAnalyticsDataClient", + "shortName": "AlphaAnalyticsDataClient" + }, + "fullName": "google.analytics.data_v1alpha.AlphaAnalyticsDataClient.chat", + "method": { + "fullName": "google.analytics.data.v1alpha.AlphaAnalyticsData.Chat", + "service": { + "fullName": "google.analytics.data.v1alpha.AlphaAnalyticsData", + "shortName": "AlphaAnalyticsData" + }, + "shortName": "Chat" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.data_v1alpha.types.ChatRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.analytics.data_v1alpha.types.ChatResponse", + "shortName": "chat" + }, + "description": "Sample for Chat", + "file": "analyticsdata_v1alpha_generated_alpha_analytics_data_chat_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsdata_v1alpha_generated_AlphaAnalyticsData_Chat_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsdata_v1alpha_generated_alpha_analytics_data_chat_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-analytics-data/tests/unit/gapic/data_v1alpha/test_alpha_analytics_data.py b/packages/google-analytics-data/tests/unit/gapic/data_v1alpha/test_alpha_analytics_data.py index c7f6fc6e044b..51fc550ea55a 100644 --- a/packages/google-analytics-data/tests/unit/gapic/data_v1alpha/test_alpha_analytics_data.py +++ b/packages/google-analytics-data/tests/unit/gapic/data_v1alpha/test_alpha_analytics_data.py @@ -1087,6 +1087,7 @@ def test_alpha_analytics_data_client_create_channel_credentials_file( quota_project_id=None, default_scopes=( "https://www.googleapis.com/auth/analytics", + "https://www.googleapis.com/auth/analytics.chatbot.read", "https://www.googleapis.com/auth/analytics.readonly", ), scopes=None, @@ -6180,6 +6181,249 @@ async def test_list_report_tasks_async_pages(): assert page_.raw_page.next_page_token == token +@pytest.mark.parametrize( + "request_type", + [ + analytics_data_api.ChatRequest(), + {}, + ], +) +def test_chat(request_type, transport: str = "grpc"): + client = AlphaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.chat), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_data_api.ChatResponse( + session_id="session_id_value", + ) + response = client.chat(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_data_api.ChatRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.ChatResponse) + assert response.session_id == "session_id_value" + + +def test_chat_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AlphaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_data_api.ChatRequest( + property="property_value", + user_query="user_query_value", + session_id="session_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.chat), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.chat(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = analytics_data_api.ChatRequest( + property="property_value", + user_query="user_query_value", + session_id="session_id_value", + ) + assert args[0] == request_msg + + +def test_chat_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AlphaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.chat in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.chat] = mock_rpc + request = {} + client.chat(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.chat(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_chat_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AlphaAnalyticsDataAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.chat in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.chat] = ( + mock_rpc + ) + + request = {} + await client.chat(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.chat(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + analytics_data_api.ChatRequest(), + {}, + ], +) +async def test_chat_async(request_type, transport: str = "grpc_asyncio"): + client = AlphaAnalyticsDataAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.chat), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_data_api.ChatResponse( + session_id="session_id_value", + ) + ) + response = await client.chat(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_data_api.ChatRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.ChatResponse) + assert response.session_id == "session_id_value" + + +def test_chat_field_headers(): + client = AlphaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_data_api.ChatRequest() + + request.property = "property_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.chat), "__call__") as call: + call.return_value = analytics_data_api.ChatResponse() + client.chat(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "property=property_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_chat_field_headers_async(): + client = AlphaAnalyticsDataAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_data_api.ChatRequest() + + request.property = "property_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.chat), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_data_api.ChatResponse() + ) + await client.chat(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "property=property_value", + ) in kw["metadata"] + + @pytest.mark.parametrize( "request_type", [ @@ -9099,6 +9343,120 @@ def test_list_report_tasks_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token +def test_chat_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AlphaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.chat in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.chat] = mock_rpc + + request = {} + client.chat(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.chat(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_chat_rest_required_fields(request_type=analytics_data_api.ChatRequest): + transport_class = transports.AlphaAnalyticsDataRestTransport + + request_init = {} + request_init["property"] = "" + request_init["user_query"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseChat, + "_BaseChat__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["property"] = "property_value" + jsonified_request["userQuery"] = "user_query_value" + + # verify required fields with non-default values are left alone + assert "property" in jsonified_request + assert jsonified_request["property"] == "property_value" + assert "userQuery" in jsonified_request + assert jsonified_request["userQuery"] == "user_query_value" + + client = AlphaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_data_api.ChatResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = analytics_data_api.ChatResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.chat(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + def test_run_report_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -9768,6 +10126,26 @@ def test_list_report_tasks_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_chat_empty_call_grpc(): + client = AlphaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.chat), "__call__") as call: + call.return_value = analytics_data_api.ChatResponse() + client.chat(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = analytics_data_api.ChatRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_run_report_empty_call_grpc(): @@ -10196,6 +10574,32 @@ async def test_list_report_tasks_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_chat_empty_call_grpc_asyncio(): + client = AlphaAnalyticsDataAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.chat), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_data_api.ChatResponse( + session_id="session_id_value", + ) + ) + await client.chat(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = analytics_data_api.ChatRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio @@ -12378,6 +12782,134 @@ def test_list_report_tasks_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_chat_rest_bad_request(request_type=analytics_data_api.ChatRequest): + client = AlphaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"property": "properties/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.chat(request) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_data_api.ChatRequest, + dict, + ], +) +def test_chat_rest_call_success(request_type): + client = AlphaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"property": "properties/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = analytics_data_api.ChatResponse( + session_id="session_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = analytics_data_api.ChatResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.chat(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_data_api.ChatResponse) + assert response.session_id == "session_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_chat_rest_interceptors(null_interceptor): + transport = transports.AlphaAnalyticsDataRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AlphaAnalyticsDataRestInterceptor(), + ) + client = AlphaAnalyticsDataClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.AlphaAnalyticsDataRestInterceptor, "post_chat" + ) as post, + mock.patch.object( + transports.AlphaAnalyticsDataRestInterceptor, "post_chat_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.AlphaAnalyticsDataRestInterceptor, "pre_chat" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = analytics_data_api.ChatRequest.pb(analytics_data_api.ChatRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = analytics_data_api.ChatResponse.to_json( + analytics_data_api.ChatResponse() + ) + req.return_value.content = return_value + + request = analytics_data_api.ChatRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_data_api.ChatResponse() + post_with_metadata.return_value = analytics_data_api.ChatResponse(), metadata + + client.chat( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_run_report_rest_bad_request(request_type=analytics_data_api.RunReportRequest): client = AlphaAnalyticsDataClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -12929,6 +13461,25 @@ def test_list_report_tasks_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_chat_empty_call_rest(): + client = AlphaAnalyticsDataClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.chat), "__call__") as call: + client.chat(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = analytics_data_api.ChatRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_run_report_empty_call_rest(): @@ -13030,6 +13581,7 @@ def test_alpha_analytics_data_base_transport(): "query_report_task", "get_report_task", "list_report_tasks", + "chat", "run_report", "get_metadata", ) @@ -13075,6 +13627,7 @@ def test_alpha_analytics_data_base_transport_with_credentials_file(): scopes=None, default_scopes=( "https://www.googleapis.com/auth/analytics", + "https://www.googleapis.com/auth/analytics.chatbot.read", "https://www.googleapis.com/auth/analytics.readonly", ), quota_project_id="octopus", @@ -13104,6 +13657,7 @@ def test_alpha_analytics_data_auth_adc(): scopes=None, default_scopes=( "https://www.googleapis.com/auth/analytics", + "https://www.googleapis.com/auth/analytics.chatbot.read", "https://www.googleapis.com/auth/analytics.readonly", ), quota_project_id=None, @@ -13127,6 +13681,7 @@ def test_alpha_analytics_data_transport_auth_adc(transport_class): scopes=["1", "2"], default_scopes=( "https://www.googleapis.com/auth/analytics", + "https://www.googleapis.com/auth/analytics.chatbot.read", "https://www.googleapis.com/auth/analytics.readonly", ), quota_project_id="octopus", @@ -13183,6 +13738,7 @@ def test_alpha_analytics_data_transport_create_channel(transport_class, grpc_hel quota_project_id="octopus", default_scopes=( "https://www.googleapis.com/auth/analytics", + "https://www.googleapis.com/auth/analytics.chatbot.read", "https://www.googleapis.com/auth/analytics.readonly", ), scopes=["1", "2"], @@ -13355,6 +13911,9 @@ def test_alpha_analytics_data_client_transport_session_collision(transport_name) session1 = client1.transport.list_report_tasks._session session2 = client2.transport.list_report_tasks._session assert session1 != session2 + session1 = client1.transport.chat._session + session2 = client2.transport.chat._session + assert session1 != session2 session1 = client1.transport.run_report._session session2 = client2.transport.run_report._session assert session1 != session2 @@ -13567,8 +14126,28 @@ def test_parse_metadata_path(): assert expected == actual -def test_property_quotas_snapshot_path(): +def test_property_path(): property = "cuttlefish" + expected = "properties/{property}".format( + property=property, + ) + actual = AlphaAnalyticsDataClient.property_path(property) + assert expected == actual + + +def test_parse_property_path(): + expected = { + "property": "mussel", + } + path = AlphaAnalyticsDataClient.property_path(**expected) + + # Check that the path construction is reversible. + actual = AlphaAnalyticsDataClient.parse_property_path(path) + assert expected == actual + + +def test_property_quotas_snapshot_path(): + property = "winkle" expected = "properties/{property}/propertyQuotasSnapshot".format( property=property, ) @@ -13578,7 +14157,7 @@ def test_property_quotas_snapshot_path(): def test_parse_property_quotas_snapshot_path(): expected = { - "property": "mussel", + "property": "nautilus", } path = AlphaAnalyticsDataClient.property_quotas_snapshot_path(**expected) @@ -13588,8 +14167,8 @@ def test_parse_property_quotas_snapshot_path(): def test_recurring_audience_list_path(): - property = "winkle" - recurring_audience_list = "nautilus" + property = "scallop" + recurring_audience_list = "abalone" expected = ( "properties/{property}/recurringAudienceLists/{recurring_audience_list}".format( property=property, @@ -13604,8 +14183,8 @@ def test_recurring_audience_list_path(): def test_parse_recurring_audience_list_path(): expected = { - "property": "scallop", - "recurring_audience_list": "abalone", + "property": "squid", + "recurring_audience_list": "clam", } path = AlphaAnalyticsDataClient.recurring_audience_list_path(**expected) @@ -13615,8 +14194,8 @@ def test_parse_recurring_audience_list_path(): def test_report_task_path(): - property = "squid" - report_task = "clam" + property = "whelk" + report_task = "octopus" expected = "properties/{property}/reportTasks/{report_task}".format( property=property, report_task=report_task, @@ -13627,8 +14206,8 @@ def test_report_task_path(): def test_parse_report_task_path(): expected = { - "property": "whelk", - "report_task": "octopus", + "property": "oyster", + "report_task": "nudibranch", } path = AlphaAnalyticsDataClient.report_task_path(**expected) @@ -13638,7 +14217,7 @@ def test_parse_report_task_path(): def test_common_billing_account_path(): - billing_account = "oyster" + billing_account = "cuttlefish" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -13648,7 +14227,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nudibranch", + "billing_account": "mussel", } path = AlphaAnalyticsDataClient.common_billing_account_path(**expected) @@ -13658,7 +14237,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "cuttlefish" + folder = "winkle" expected = "folders/{folder}".format( folder=folder, ) @@ -13668,7 +14247,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "mussel", + "folder": "nautilus", } path = AlphaAnalyticsDataClient.common_folder_path(**expected) @@ -13678,7 +14257,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "winkle" + organization = "scallop" expected = "organizations/{organization}".format( organization=organization, ) @@ -13688,7 +14267,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nautilus", + "organization": "abalone", } path = AlphaAnalyticsDataClient.common_organization_path(**expected) @@ -13698,7 +14277,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "scallop" + project = "squid" expected = "projects/{project}".format( project=project, ) @@ -13708,7 +14287,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "abalone", + "project": "clam", } path = AlphaAnalyticsDataClient.common_project_path(**expected) @@ -13718,8 +14297,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "squid" - location = "clam" + project = "whelk" + location = "octopus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -13730,8 +14309,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "whelk", - "location": "octopus", + "project": "oyster", + "location": "nudibranch", } path = AlphaAnalyticsDataClient.common_location_path(**expected) diff --git a/packages/google-apps-chat/google/apps/chat/__init__.py b/packages/google-apps-chat/google/apps/chat/__init__.py index 8c566412a596..43f1bbe5ac5e 100644 --- a/packages/google-apps-chat/google/apps/chat/__init__.py +++ b/packages/google-apps-chat/google/apps/chat/__init__.py @@ -35,6 +35,7 @@ SlashCommandMetadata, UserMentionMetadata, ) +from google.apps.chat_v1.types.app_command_metadata import AppCommandMetadata from google.apps.chat_v1.types.attachment import ( Attachment, AttachmentDataRef, @@ -112,6 +113,13 @@ Thread, UpdateMessageRequest, ) +from google.apps.chat_v1.types.message_pin import ( + CreateMessagePinRequest, + DeleteMessagePinRequest, + ListMessagePinsRequest, + ListMessagePinsResponse, + MessagePin, +) from google.apps.chat_v1.types.reaction import ( CreateCustomEmojiRequest, CreateReactionRequest, @@ -198,6 +206,7 @@ "SlashCommandMetadata", "UserMentionMetadata", "AnnotationType", + "AppCommandMetadata", "Attachment", "AttachmentDataRef", "DriveDataRef", @@ -265,6 +274,11 @@ "SearchMessagesResponse", "Thread", "UpdateMessageRequest", + "CreateMessagePinRequest", + "DeleteMessagePinRequest", + "ListMessagePinsRequest", + "ListMessagePinsResponse", + "MessagePin", "CreateCustomEmojiRequest", "CreateReactionRequest", "CustomEmoji", diff --git a/packages/google-apps-chat/google/apps/chat_v1/__init__.py b/packages/google-apps-chat/google/apps/chat_v1/__init__.py index 30ce77a14cb6..087e18e1cc71 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/__init__.py +++ b/packages/google-apps-chat/google/apps/chat_v1/__init__.py @@ -29,6 +29,7 @@ "google.apps.chat_v1.services.chat_service", "google.apps.chat_v1.types.action_status", "google.apps.chat_v1.types.annotation", + "google.apps.chat_v1.types.app_command_metadata", "google.apps.chat_v1.types.attachment", "google.apps.chat_v1.types.audience", "google.apps.chat_v1.types.availability", @@ -42,6 +43,7 @@ "google.apps.chat_v1.types.matched_url", "google.apps.chat_v1.types.membership", "google.apps.chat_v1.types.message", + "google.apps.chat_v1.types.message_pin", "google.apps.chat_v1.types.reaction", "google.apps.chat_v1.types.section", "google.apps.chat_v1.types.slash_command", @@ -70,6 +72,7 @@ SlashCommandMetadata, UserMentionMetadata, ) +from .types.app_command_metadata import AppCommandMetadata from .types.attachment import ( Attachment, AttachmentDataRef, @@ -147,6 +150,13 @@ Thread, UpdateMessageRequest, ) +from .types.message_pin import ( + CreateMessagePinRequest, + DeleteMessagePinRequest, + ListMessagePinsRequest, + ListMessagePinsResponse, + MessagePin, +) from .types.reaction import ( CreateCustomEmojiRequest, CreateReactionRequest, @@ -223,6 +233,7 @@ "ActionStatus", "Annotation", "AnnotationType", + "AppCommandMetadata", "AttachedGif", "Attachment", "AttachmentDataRef", @@ -238,6 +249,7 @@ "CreateCustomEmojiRequest", "CreateMembershipRequest", "CreateMessageNotificationOptions", + "CreateMessagePinRequest", "CreateMessageRequest", "CreateReactionRequest", "CreateSectionRequest", @@ -247,6 +259,7 @@ "CustomStatus", "DeleteCustomEmojiRequest", "DeleteMembershipRequest", + "DeleteMessagePinRequest", "DeleteMessageRequest", "DeleteReactionRequest", "DeleteSectionRequest", @@ -279,6 +292,8 @@ "ListCustomEmojisResponse", "ListMembershipsRequest", "ListMembershipsResponse", + "ListMessagePinsRequest", + "ListMessagePinsResponse", "ListMessagesRequest", "ListMessagesResponse", "ListReactionsRequest", @@ -310,6 +325,7 @@ "MessageBatchUpdatedEventData", "MessageCreatedEventData", "MessageDeletedEventData", + "MessagePin", "MessageUpdatedEventData", "MoveSectionItemRequest", "MoveSectionItemResponse", diff --git a/packages/google-apps-chat/google/apps/chat_v1/gapic_metadata.json b/packages/google-apps-chat/google/apps/chat_v1/gapic_metadata.json index 7e39ee4c5808..8f3b262be9eb 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/gapic_metadata.json +++ b/packages/google-apps-chat/google/apps/chat_v1/gapic_metadata.json @@ -30,6 +30,11 @@ "create_message" ] }, + "CreateMessagePin": { + "methods": [ + "create_message_pin" + ] + }, "CreateReaction": { "methods": [ "create_reaction" @@ -60,6 +65,11 @@ "delete_message" ] }, + "DeleteMessagePin": { + "methods": [ + "delete_message_pin" + ] + }, "DeleteReaction": { "methods": [ "delete_reaction" @@ -145,6 +155,11 @@ "list_memberships" ] }, + "ListMessagePins": { + "methods": [ + "list_message_pins" + ] + }, "ListMessages": { "methods": [ "list_messages" @@ -280,6 +295,11 @@ "create_message" ] }, + "CreateMessagePin": { + "methods": [ + "create_message_pin" + ] + }, "CreateReaction": { "methods": [ "create_reaction" @@ -310,6 +330,11 @@ "delete_message" ] }, + "DeleteMessagePin": { + "methods": [ + "delete_message_pin" + ] + }, "DeleteReaction": { "methods": [ "delete_reaction" @@ -395,6 +420,11 @@ "list_memberships" ] }, + "ListMessagePins": { + "methods": [ + "list_message_pins" + ] + }, "ListMessages": { "methods": [ "list_messages" @@ -530,6 +560,11 @@ "create_message" ] }, + "CreateMessagePin": { + "methods": [ + "create_message_pin" + ] + }, "CreateReaction": { "methods": [ "create_reaction" @@ -560,6 +595,11 @@ "delete_message" ] }, + "DeleteMessagePin": { + "methods": [ + "delete_message_pin" + ] + }, "DeleteReaction": { "methods": [ "delete_reaction" @@ -645,6 +685,11 @@ "list_memberships" ] }, + "ListMessagePins": { + "methods": [ + "list_message_pins" + ] + }, "ListMessages": { "methods": [ "list_messages" diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/async_client.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/async_client.py index 8ce5049b3136..de6241dbba80 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/async_client.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/async_client.py @@ -61,6 +61,7 @@ matched_url, membership, message, + message_pin, reaction, section, slash_command, @@ -75,6 +76,7 @@ from google.apps.chat_v1.types import availability as gc_availability from google.apps.chat_v1.types import membership as gc_membership from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import message_pin as gc_message_pin from google.apps.chat_v1.types import reaction as gc_reaction from google.apps.chat_v1.types import section as gc_section from google.apps.chat_v1.types import space as gc_space @@ -121,6 +123,8 @@ class ChatServiceAsyncClient: parse_membership_path = staticmethod(ChatServiceClient.parse_membership_path) message_path = staticmethod(ChatServiceClient.message_path) parse_message_path = staticmethod(ChatServiceClient.parse_message_path) + message_pin_path = staticmethod(ChatServiceClient.message_pin_path) + parse_message_pin_path = staticmethod(ChatServiceClient.parse_message_pin_path) quoted_message_metadata_path = staticmethod( ChatServiceClient.quoted_message_metadata_path ) @@ -1592,6 +1596,11 @@ async def sample_search_messages(): ``space.display_name:Project`` searches for messages in the top five spaces that contain the word "Project" in their display names. + - ``space.space_type``: The type of the space. Only + supports ``=``. For example, + ``space.space_type="DIRECT_MESSAGE"`` returns only + messages from direct messages. The possible values are + ``DIRECT_MESSAGE``, ``GROUP_CHAT``, and ``SPACE``. - ``attachment``: Supports the operator ``:*`` (has any) to check for the presence of attachments. If ``attachment:*`` is specified, only messages that have @@ -1616,9 +1625,9 @@ async def sample_search_messages(): - ``is_unread()``: Filters out messages that have been read by the calling user. - Using the ``space.display_name`` filter requires that - the calling credentials include one of the following - `authorization + Using the ``space.display_name`` or the + ``space.space_type`` filters requires that the calling + credentials include one of the following `authorization scopes `__: - ``https://www.googleapis.com/auth/chat.spaces.readonly`` @@ -1663,6 +1672,9 @@ async def sample_search_messages(): ``space.display_name:Project OR space.display_name:Tasks`` returns messages that are in spaces with display names containing either ``Project`` or ``Tasks`` or both. + - ``space.space_type`` supports only the ``OR`` + operator, for example: + ``space.space_type = "DIRECT_MESSAGE" OR space.space_type = "GROUP_CHAT"``. - ``annotations.user_mentions.user.name`` supports the operators ``AND`` and ``OR``, but not a mix of both. For example: @@ -2885,6 +2897,7 @@ async def sample_update_space(): - ``access_settings.access_permission_settings.discoverSpaceSetting`` - ``access_settings.access_permission_settings.joinSpaceSetting`` + - ``access_settings.access_permission_settings.viewSpaceMembershipSetting`` ``permission_settings``: Supports changing the `permission @@ -2901,6 +2914,7 @@ async def sample_update_space(): - ``permission_settings.manageApps`` - ``permission_settings.manageWebhooks`` - ``permission_settings.replyMessages`` + - ``permission_settings.viewSpaceMembership`` This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this @@ -4355,6 +4369,384 @@ async def sample_delete_reaction(): metadata=metadata, ) + async def list_message_pins( + self, + request: Optional[Union[message_pin.ListMessagePinsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMessagePinsAsyncPager: + r"""Lists message pins in a space. Users can pin important messages + in spaces for easy access. For more information, see `Pin or + unpin a conversation in Google + Chat `__. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.spaces.pins.readonly`` + - ``https://www.googleapis.com/auth/chat.spaces.pins`` + - ``https://www.googleapis.com/auth/chat.spaces.readonly`` + - ``https://www.googleapis.com/auth/chat.spaces`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_list_message_pins(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListMessagePinsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_pins(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.ListMessagePinsRequest, dict]]): + The request object. Request message for listing message + pins. + parent (:class:`str`): + Required. The parent space which owns the collection of + pinned items Format: ``spaces/{space}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.chat_v1.services.chat_service.pagers.ListMessagePinsAsyncPager: + Response message for listing message + pins. + 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. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, message_pin.ListMessagePinsRequest): + request = message_pin.ListMessagePinsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_message_pins + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListMessagePinsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_message_pin( + self, + request: Optional[Union[gc_message_pin.CreateMessagePinRequest, dict]] = None, + *, + parent: Optional[str] = None, + message_pin: Optional[gc_message_pin.MessagePin] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gc_message_pin.MessagePin: + r"""Creates a message pin. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.spaces.pins`` + - ``https://www.googleapis.com/auth/chat.spaces`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_create_message_pin(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + message_pin = chat_v1.MessagePin() + message_pin.message = "message_value" + + request = chat_v1.CreateMessagePinRequest( + parent="parent_value", + message_pin=message_pin, + ) + + # Make the request + response = await client.create_message_pin(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.CreateMessagePinRequest, dict]]): + The request object. Request message for creating a + message pin. + parent (:class:`str`): + Required. The parent space in which + to create the message pin. Format: + spaces/{space} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message_pin (:class:`google.apps.chat_v1.types.MessagePin`): + Required. The MessagePin to create. + This corresponds to the ``message_pin`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.chat_v1.types.MessagePin: + A pin on a Chat message. For more information see [Pin a + message](https://support.google.com/chat?p=chat-board-hc). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, message_pin] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gc_message_pin.CreateMessagePinRequest): + request = gc_message_pin.CreateMessagePinRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if message_pin is not None: + request.message_pin = message_pin + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_message_pin + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_message_pin( + self, + request: Optional[Union[message_pin.DeleteMessagePinRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a message pin. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.spaces.pins`` + - ``https://www.googleapis.com/auth/chat.spaces`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + async def sample_delete_message_pin(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMessagePinRequest( + name="name_value", + ) + + # Make the request + await client.delete_message_pin(request=request) + + Args: + request (Optional[Union[google.apps.chat_v1.types.DeleteMessagePinRequest, dict]]): + The request object. Request message for deleting a + message pin. + name (:class:`str`): + Required. The resource name of the message pin to + remove. Format: spaces/{space}/messagePins/{message_pin} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, message_pin.DeleteMessagePinRequest): + request = message_pin.DeleteMessagePinRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_message_pin + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + async def create_custom_emoji( self, request: Optional[Union[reaction.CreateCustomEmojiRequest, dict]] = None, diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py index cb461a881caa..0519407e523c 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py @@ -85,6 +85,7 @@ matched_url, membership, message, + message_pin, reaction, section, slash_command, @@ -99,6 +100,7 @@ from google.apps.chat_v1.types import availability as gc_availability from google.apps.chat_v1.types import membership as gc_membership from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import message_pin as gc_message_pin from google.apps.chat_v1.types import reaction as gc_reaction from google.apps.chat_v1.types import section as gc_section from google.apps.chat_v1.types import space as gc_space @@ -293,6 +295,23 @@ def parse_message_path(path: str) -> Dict[str, str]: m = re.match(r"^spaces/(?P.+?)/messages/(?P.+?)$", path) return m.groupdict() if m else {} + @staticmethod + def message_pin_path( + space: str, + message_pin: str, + ) -> str: + """Returns a fully-qualified message_pin string.""" + return "spaces/{space}/messagePins/{message_pin}".format( + space=space, + message_pin=message_pin, + ) + + @staticmethod + def parse_message_pin_path(path: str) -> Dict[str, str]: + """Parses a message_pin path into its component segments.""" + m = re.match(r"^spaces/(?P.+?)/messagePins/(?P.+?)$", path) + return m.groupdict() if m else {} + @staticmethod def quoted_message_metadata_path( space: str, @@ -2101,6 +2120,11 @@ def sample_search_messages(): ``space.display_name:Project`` searches for messages in the top five spaces that contain the word "Project" in their display names. + - ``space.space_type``: The type of the space. Only + supports ``=``. For example, + ``space.space_type="DIRECT_MESSAGE"`` returns only + messages from direct messages. The possible values are + ``DIRECT_MESSAGE``, ``GROUP_CHAT``, and ``SPACE``. - ``attachment``: Supports the operator ``:*`` (has any) to check for the presence of attachments. If ``attachment:*`` is specified, only messages that have @@ -2125,9 +2149,9 @@ def sample_search_messages(): - ``is_unread()``: Filters out messages that have been read by the calling user. - Using the ``space.display_name`` filter requires that - the calling credentials include one of the following - `authorization + Using the ``space.display_name`` or the + ``space.space_type`` filters requires that the calling + credentials include one of the following `authorization scopes `__: - ``https://www.googleapis.com/auth/chat.spaces.readonly`` @@ -2172,6 +2196,9 @@ def sample_search_messages(): ``space.display_name:Project OR space.display_name:Tasks`` returns messages that are in spaces with display names containing either ``Project`` or ``Tasks`` or both. + - ``space.space_type`` supports only the ``OR`` + operator, for example: + ``space.space_type = "DIRECT_MESSAGE" OR space.space_type = "GROUP_CHAT"``. - ``annotations.user_mentions.user.name`` supports the operators ``AND`` and ``OR``, but not a mix of both. For example: @@ -3374,6 +3401,7 @@ def sample_update_space(): - ``access_settings.access_permission_settings.discoverSpaceSetting`` - ``access_settings.access_permission_settings.joinSpaceSetting`` + - ``access_settings.access_permission_settings.viewSpaceMembershipSetting`` ``permission_settings``: Supports changing the `permission @@ -3390,6 +3418,7 @@ def sample_update_space(): - ``permission_settings.manageApps`` - ``permission_settings.manageWebhooks`` - ``permission_settings.replyMessages`` + - ``permission_settings.viewSpaceMembership`` This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this @@ -4814,6 +4843,375 @@ def sample_delete_reaction(): metadata=metadata, ) + def list_message_pins( + self, + request: Optional[Union[message_pin.ListMessagePinsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMessagePinsPager: + r"""Lists message pins in a space. Users can pin important messages + in spaces for easy access. For more information, see `Pin or + unpin a conversation in Google + Chat `__. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.spaces.pins.readonly`` + - ``https://www.googleapis.com/auth/chat.spaces.pins`` + - ``https://www.googleapis.com/auth/chat.spaces.readonly`` + - ``https://www.googleapis.com/auth/chat.spaces`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_list_message_pins(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListMessagePinsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_pins(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.apps.chat_v1.types.ListMessagePinsRequest, dict]): + The request object. Request message for listing message + pins. + parent (str): + Required. The parent space which owns the collection of + pinned items Format: ``spaces/{space}`` + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.chat_v1.services.chat_service.pagers.ListMessagePinsPager: + Response message for listing message + pins. + 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. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, message_pin.ListMessagePinsRequest): + request = message_pin.ListMessagePinsRequest(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_message_pins] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListMessagePinsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_message_pin( + self, + request: Optional[Union[gc_message_pin.CreateMessagePinRequest, dict]] = None, + *, + parent: Optional[str] = None, + message_pin: Optional[gc_message_pin.MessagePin] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gc_message_pin.MessagePin: + r"""Creates a message pin. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.spaces.pins`` + - ``https://www.googleapis.com/auth/chat.spaces`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_create_message_pin(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + message_pin = chat_v1.MessagePin() + message_pin.message = "message_value" + + request = chat_v1.CreateMessagePinRequest( + parent="parent_value", + message_pin=message_pin, + ) + + # Make the request + response = client.create_message_pin(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.CreateMessagePinRequest, dict]): + The request object. Request message for creating a + message pin. + parent (str): + Required. The parent space in which + to create the message pin. Format: + spaces/{space} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message_pin (google.apps.chat_v1.types.MessagePin): + Required. The MessagePin to create. + This corresponds to the ``message_pin`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.apps.chat_v1.types.MessagePin: + A pin on a Chat message. For more information see [Pin a + message](https://support.google.com/chat?p=chat-board-hc). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, message_pin] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gc_message_pin.CreateMessagePinRequest): + request = gc_message_pin.CreateMessagePinRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if message_pin is not None: + request.message_pin = message_pin + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_message_pin] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_message_pin( + self, + request: Optional[Union[message_pin.DeleteMessagePinRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a message pin. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.spaces.pins`` + - ``https://www.googleapis.com/auth/chat.spaces`` + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.apps import chat_v1 + + def sample_delete_message_pin(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMessagePinRequest( + name="name_value", + ) + + # Make the request + client.delete_message_pin(request=request) + + Args: + request (Union[google.apps.chat_v1.types.DeleteMessagePinRequest, dict]): + The request object. Request message for deleting a + message pin. + name (str): + Required. The resource name of the message pin to + remove. Format: spaces/{space}/messagePins/{message_pin} + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, message_pin.DeleteMessagePinRequest): + request = message_pin.DeleteMessagePinRequest(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_message_pin] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + def create_custom_emoji( self, request: Optional[Union[reaction.CreateCustomEmojiRequest, dict]] = None, diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/pagers.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/pagers.py index 29a9dd32f3fb..7eaae4342236 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/pagers.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/pagers.py @@ -41,6 +41,7 @@ from google.apps.chat_v1.types import ( membership, message, + message_pin, reaction, section, space, @@ -1140,6 +1141,162 @@ def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) +class ListMessagePinsPager: + """A pager for iterating through ``list_message_pins`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListMessagePinsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``message_pins`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMessagePins`` requests and continue to iterate + through the ``message_pins`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListMessagePinsResponse` + 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[..., message_pin.ListMessagePinsResponse], + request: message_pin.ListMessagePinsRequest, + response: message_pin.ListMessagePinsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.chat_v1.types.ListMessagePinsRequest): + The initial request object. + response (google.apps.chat_v1.types.ListMessagePinsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = message_pin.ListMessagePinsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[message_pin.ListMessagePinsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[message_pin.MessagePin]: + for page in self.pages: + yield from page.message_pins + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMessagePinsAsyncPager: + """A pager for iterating through ``list_message_pins`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListMessagePinsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``message_pins`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMessagePins`` requests and continue to iterate + through the ``message_pins`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListMessagePinsResponse` + 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[message_pin.ListMessagePinsResponse]], + request: message_pin.ListMessagePinsRequest, + response: message_pin.ListMessagePinsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.chat_v1.types.ListMessagePinsRequest): + The initial request object. + response (google.apps.chat_v1.types.ListMessagePinsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = message_pin.ListMessagePinsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[message_pin.ListMessagePinsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[message_pin.MessagePin]: + async def async_generator(): + async for page in self.pages: + for response in page.message_pins: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class ListCustomEmojisPager: """A pager for iterating through ``list_custom_emojis`` requests. diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/base.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/base.py index 809967268be4..2651466299d1 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/base.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/base.py @@ -32,6 +32,7 @@ availability, membership, message, + message_pin, reaction, section, space, @@ -44,6 +45,7 @@ from google.apps.chat_v1.types import availability as gc_availability from google.apps.chat_v1.types import membership as gc_membership from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import message_pin as gc_message_pin from google.apps.chat_v1.types import reaction as gc_reaction from google.apps.chat_v1.types import section as gc_section from google.apps.chat_v1.types import space as gc_space @@ -93,6 +95,8 @@ class ChatServiceTransport(abc.ABC): "https://www.googleapis.com/auth/chat.messages.readonly", "https://www.googleapis.com/auth/chat.spaces", "https://www.googleapis.com/auth/chat.spaces.create", + "https://www.googleapis.com/auth/chat.spaces.pins", + "https://www.googleapis.com/auth/chat.spaces.pins.readonly", "https://www.googleapis.com/auth/chat.spaces.readonly", "https://www.googleapis.com/auth/chat.users.availability", "https://www.googleapis.com/auth/chat.users.availability.readonly", @@ -568,6 +572,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=30.0, client_info=client_info, ), + self.list_message_pins: gapic_v1.method.wrap_method( + self.list_message_pins, + default_timeout=None, + client_info=client_info, + ), + self.create_message_pin: gapic_v1.method.wrap_method( + self.create_message_pin, + default_timeout=None, + client_info=client_info, + ), + self.delete_message_pin: gapic_v1.method.wrap_method( + self.delete_message_pin, + default_timeout=None, + client_info=client_info, + ), self.create_custom_emoji: gapic_v1.method.wrap_method( self.create_custom_emoji, default_retry=retries.Retry( @@ -1139,6 +1158,36 @@ def delete_reaction( ]: raise NotImplementedError() + @property + def list_message_pins( + self, + ) -> Callable[ + [message_pin.ListMessagePinsRequest], + Union[ + message_pin.ListMessagePinsResponse, + Awaitable[message_pin.ListMessagePinsResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_message_pin( + self, + ) -> Callable[ + [gc_message_pin.CreateMessagePinRequest], + Union[gc_message_pin.MessagePin, Awaitable[gc_message_pin.MessagePin]], + ]: + raise NotImplementedError() + + @property + def delete_message_pin( + self, + ) -> Callable[ + [message_pin.DeleteMessagePinRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + @property def create_custom_emoji( self, diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc.py index 4fed39a8894b..ffccd6cf7d36 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc.py @@ -34,6 +34,7 @@ availability, membership, message, + message_pin, reaction, section, space, @@ -46,6 +47,7 @@ from google.apps.chat_v1.types import availability as gc_availability from google.apps.chat_v1.types import membership as gc_membership from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import message_pin as gc_message_pin from google.apps.chat_v1.types import reaction as gc_reaction from google.apps.chat_v1.types import section as gc_section from google.apps.chat_v1.types import space as gc_space @@ -1774,6 +1776,115 @@ def delete_reaction( ) return self._stubs["delete_reaction"] + @property + def list_message_pins( + self, + ) -> Callable[ + [message_pin.ListMessagePinsRequest], message_pin.ListMessagePinsResponse + ]: + r"""Return a callable for the list message pins method over gRPC. + + Lists message pins in a space. Users can pin important messages + in spaces for easy access. For more information, see `Pin or + unpin a conversation in Google + Chat `__. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.spaces.pins.readonly`` + - ``https://www.googleapis.com/auth/chat.spaces.pins`` + - ``https://www.googleapis.com/auth/chat.spaces.readonly`` + - ``https://www.googleapis.com/auth/chat.spaces`` + + Returns: + Callable[[~.ListMessagePinsRequest], + ~.ListMessagePinsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_message_pins" not in self._stubs: + self._stubs["list_message_pins"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/ListMessagePins", + request_serializer=message_pin.ListMessagePinsRequest.serialize, + response_deserializer=message_pin.ListMessagePinsResponse.deserialize, + ) + return self._stubs["list_message_pins"] + + @property + def create_message_pin( + self, + ) -> Callable[[gc_message_pin.CreateMessagePinRequest], gc_message_pin.MessagePin]: + r"""Return a callable for the create message pin method over gRPC. + + Creates a message pin. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.spaces.pins`` + - ``https://www.googleapis.com/auth/chat.spaces`` + + Returns: + Callable[[~.CreateMessagePinRequest], + ~.MessagePin]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_message_pin" not in self._stubs: + self._stubs["create_message_pin"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/CreateMessagePin", + request_serializer=gc_message_pin.CreateMessagePinRequest.serialize, + response_deserializer=gc_message_pin.MessagePin.deserialize, + ) + return self._stubs["create_message_pin"] + + @property + def delete_message_pin( + self, + ) -> Callable[[message_pin.DeleteMessagePinRequest], empty_pb2.Empty]: + r"""Return a callable for the delete message pin method over gRPC. + + Deletes a message pin. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.spaces.pins`` + - ``https://www.googleapis.com/auth/chat.spaces`` + + Returns: + Callable[[~.DeleteMessagePinRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_message_pin" not in self._stubs: + self._stubs["delete_message_pin"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/DeleteMessagePin", + request_serializer=message_pin.DeleteMessagePinRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_message_pin"] + @property def create_custom_emoji( self, diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py index cda70dd62bd1..eeb2cb0838ca 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py @@ -37,6 +37,7 @@ availability, membership, message, + message_pin, reaction, section, space, @@ -49,6 +50,7 @@ from google.apps.chat_v1.types import availability as gc_availability from google.apps.chat_v1.types import membership as gc_membership from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import message_pin as gc_message_pin from google.apps.chat_v1.types import reaction as gc_reaction from google.apps.chat_v1.types import section as gc_section from google.apps.chat_v1.types import space as gc_space @@ -1808,6 +1810,118 @@ def delete_reaction( ) return self._stubs["delete_reaction"] + @property + def list_message_pins( + self, + ) -> Callable[ + [message_pin.ListMessagePinsRequest], + Awaitable[message_pin.ListMessagePinsResponse], + ]: + r"""Return a callable for the list message pins method over gRPC. + + Lists message pins in a space. Users can pin important messages + in spaces for easy access. For more information, see `Pin or + unpin a conversation in Google + Chat `__. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.spaces.pins.readonly`` + - ``https://www.googleapis.com/auth/chat.spaces.pins`` + - ``https://www.googleapis.com/auth/chat.spaces.readonly`` + - ``https://www.googleapis.com/auth/chat.spaces`` + + Returns: + Callable[[~.ListMessagePinsRequest], + Awaitable[~.ListMessagePinsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_message_pins" not in self._stubs: + self._stubs["list_message_pins"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/ListMessagePins", + request_serializer=message_pin.ListMessagePinsRequest.serialize, + response_deserializer=message_pin.ListMessagePinsResponse.deserialize, + ) + return self._stubs["list_message_pins"] + + @property + def create_message_pin( + self, + ) -> Callable[ + [gc_message_pin.CreateMessagePinRequest], Awaitable[gc_message_pin.MessagePin] + ]: + r"""Return a callable for the create message pin method over gRPC. + + Creates a message pin. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.spaces.pins`` + - ``https://www.googleapis.com/auth/chat.spaces`` + + Returns: + Callable[[~.CreateMessagePinRequest], + Awaitable[~.MessagePin]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_message_pin" not in self._stubs: + self._stubs["create_message_pin"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/CreateMessagePin", + request_serializer=gc_message_pin.CreateMessagePinRequest.serialize, + response_deserializer=gc_message_pin.MessagePin.deserialize, + ) + return self._stubs["create_message_pin"] + + @property + def delete_message_pin( + self, + ) -> Callable[[message_pin.DeleteMessagePinRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete message pin method over gRPC. + + Deletes a message pin. + + Requires `user + authentication `__ + with one of the following `authorization + scopes `__: + + - ``https://www.googleapis.com/auth/chat.spaces.pins`` + - ``https://www.googleapis.com/auth/chat.spaces`` + + Returns: + Callable[[~.DeleteMessagePinRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_message_pin" not in self._stubs: + self._stubs["delete_message_pin"] = self._logged_channel.unary_unary( + "/google.chat.v1.ChatService/DeleteMessagePin", + request_serializer=message_pin.DeleteMessagePinRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_message_pin"] + @property def create_custom_emoji( self, @@ -3168,6 +3282,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=30.0, client_info=client_info, ), + self.list_message_pins: self._wrap_method( + self.list_message_pins, + default_timeout=None, + client_info=client_info, + ), + self.create_message_pin: self._wrap_method( + self.create_message_pin, + default_timeout=None, + client_info=client_info, + ), + self.delete_message_pin: self._wrap_method( + self.delete_message_pin, + default_timeout=None, + client_info=client_info, + ), self.create_custom_emoji: self._wrap_method( self.create_custom_emoji, default_retry=retries.AsyncRetry( diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest.py index dfae911532aa..fb7ddee2cf08 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest.py @@ -35,6 +35,7 @@ availability, membership, message, + message_pin, reaction, section, space, @@ -47,6 +48,7 @@ from google.apps.chat_v1.types import availability as gc_availability from google.apps.chat_v1.types import membership as gc_membership from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import message_pin as gc_message_pin from google.apps.chat_v1.types import reaction as gc_reaction from google.apps.chat_v1.types import section as gc_section from google.apps.chat_v1.types import space as gc_space @@ -128,6 +130,14 @@ def post_create_message(self, response): logging.log(f"Received response: {response}") return response + def pre_create_message_pin(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_message_pin(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_reaction(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -168,6 +178,10 @@ def pre_delete_message(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata + def pre_delete_message_pin(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + def pre_delete_reaction(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -292,6 +306,14 @@ def post_list_memberships(self, response): logging.log(f"Received response: {response}") return response + def pre_list_message_pins(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_message_pins(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_messages(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -666,6 +688,54 @@ def post_create_message_with_metadata( """ return response, metadata + def pre_create_message_pin( + self, + request: gc_message_pin.CreateMessagePinRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gc_message_pin.CreateMessagePinRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_message_pin + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_create_message_pin( + self, response: gc_message_pin.MessagePin + ) -> gc_message_pin.MessagePin: + """Post-rpc interceptor for create_message_pin + + DEPRECATED. Please use the `post_create_message_pin_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. This `post_create_message_pin` interceptor runs + before the `post_create_message_pin_with_metadata` interceptor. + """ + return response + + def post_create_message_pin_with_metadata( + self, + response: gc_message_pin.MessagePin, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gc_message_pin.MessagePin, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_message_pin + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ChatService server but before it is returned to user code. + + We recommend only using this `post_create_message_pin_with_metadata` + interceptor in new development instead of the `post_create_message_pin` interceptor. + When both interceptors are used, this `post_create_message_pin_with_metadata` interceptor runs after the + `post_create_message_pin` interceptor. The (possibly modified) response returned by + `post_create_message_pin` will be passed to + `post_create_message_pin_with_metadata`. + """ + return response, metadata + def pre_create_reaction( self, request: gc_reaction.CreateReactionRequest, @@ -878,6 +948,20 @@ def pre_delete_message( """ return request, metadata + def pre_delete_message_pin( + self, + request: message_pin.DeleteMessagePinRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + message_pin.DeleteMessagePinRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_message_pin + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + def pre_delete_reaction( self, request: reaction.DeleteReactionRequest, @@ -1580,6 +1664,56 @@ def post_list_memberships_with_metadata( """ return response, metadata + def pre_list_message_pins( + self, + request: message_pin.ListMessagePinsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + message_pin.ListMessagePinsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_message_pins + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_list_message_pins( + self, response: message_pin.ListMessagePinsResponse + ) -> message_pin.ListMessagePinsResponse: + """Post-rpc interceptor for list_message_pins + + DEPRECATED. Please use the `post_list_message_pins_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. This `post_list_message_pins` interceptor runs + before the `post_list_message_pins_with_metadata` interceptor. + """ + return response + + def post_list_message_pins_with_metadata( + self, + response: message_pin.ListMessagePinsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + message_pin.ListMessagePinsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_message_pins + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ChatService server but before it is returned to user code. + + We recommend only using this `post_list_message_pins_with_metadata` + interceptor in new development instead of the `post_list_message_pins` interceptor. + When both interceptors are used, this `post_list_message_pins_with_metadata` interceptor runs after the + `post_list_message_pins` interceptor. The (possibly modified) response returned by + `post_list_message_pins` will be passed to + `post_list_message_pins_with_metadata`. + """ + return response, metadata + def pre_list_messages( self, request: message.ListMessagesRequest, @@ -3321,6 +3455,158 @@ def __call__( ) return resp + class _CreateMessagePin( + _BaseChatServiceRestTransport._BaseCreateMessagePin, ChatServiceRestStub + ): + def __hash__(self): + return hash("ChatServiceRestTransport.CreateMessagePin") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gc_message_pin.CreateMessagePinRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gc_message_pin.MessagePin: + r"""Call the create message pin method over HTTP. + + Args: + request (~.gc_message_pin.CreateMessagePinRequest): + The request object. Request message for creating a + message pin. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gc_message_pin.MessagePin: + A pin on a Chat message. For more information see `Pin a + message `__. + + """ + + http_options = ( + _BaseChatServiceRestTransport._BaseCreateMessagePin._get_http_options() + ) + request, metadata = self._interceptor.pre_create_message_pin( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseChatServiceRestTransport._BaseCreateMessagePin, + "_BaseCreateMessagePin__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.chat_v1.ChatServiceClient.CreateMessagePin", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "CreateMessagePin", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ChatServiceRestTransport._CreateMessagePin._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gc_message_pin.MessagePin() + pb_resp = gc_message_pin.MessagePin.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_message_pin(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_message_pin_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gc_message_pin.MessagePin.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.chat_v1.ChatServiceClient.create_message_pin", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "CreateMessagePin", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _CreateReaction( _BaseChatServiceRestTransport._BaseCreateReaction, ChatServiceRestStub ): @@ -4156,6 +4442,116 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + class _DeleteMessagePin( + _BaseChatServiceRestTransport._BaseDeleteMessagePin, ChatServiceRestStub + ): + def __hash__(self): + return hash("ChatServiceRestTransport.DeleteMessagePin") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: message_pin.DeleteMessagePinRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete message pin method over HTTP. + + Args: + request (~.message_pin.DeleteMessagePinRequest): + The request object. Request message for deleting a + message pin. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseChatServiceRestTransport._BaseDeleteMessagePin._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_message_pin( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseChatServiceRestTransport._BaseDeleteMessagePin, + "_BaseDeleteMessagePin__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.chat_v1.ChatServiceClient.DeleteMessagePin", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "DeleteMessagePin", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ChatServiceRestTransport._DeleteMessagePin._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + class _DeleteReaction( _BaseChatServiceRestTransport._BaseDeleteReaction, ChatServiceRestStub ): @@ -6584,6 +6980,158 @@ def __call__( ) return resp + class _ListMessagePins( + _BaseChatServiceRestTransport._BaseListMessagePins, ChatServiceRestStub + ): + def __hash__(self): + return hash("ChatServiceRestTransport.ListMessagePins") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: message_pin.ListMessagePinsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> message_pin.ListMessagePinsResponse: + r"""Call the list message pins method over HTTP. + + Args: + request (~.message_pin.ListMessagePinsRequest): + The request object. Request message for listing message + pins. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.message_pin.ListMessagePinsResponse: + Response message for listing message + pins. + + """ + + http_options = ( + _BaseChatServiceRestTransport._BaseListMessagePins._get_http_options() + ) + request, metadata = self._interceptor.pre_list_message_pins( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseChatServiceRestTransport._BaseListMessagePins, + "_BaseListMessagePins__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.chat_v1.ChatServiceClient.ListMessagePins", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "ListMessagePins", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ChatServiceRestTransport._ListMessagePins._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = message_pin.ListMessagePinsResponse() + pb_resp = message_pin.ListMessagePinsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_message_pins(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_message_pins_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = message_pin.ListMessagePinsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.chat_v1.ChatServiceClient.list_message_pins", + extra={ + "serviceName": "google.chat.v1.ChatService", + "rpcName": "ListMessagePins", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _ListMessages( _BaseChatServiceRestTransport._BaseListMessages, ChatServiceRestStub ): @@ -9959,6 +10507,14 @@ def create_message( # In C++ this would require a dynamic_cast return self._CreateMessage(self._session, self._host, self._interceptor) # type: ignore + @property + def create_message_pin( + self, + ) -> Callable[[gc_message_pin.CreateMessagePinRequest], gc_message_pin.MessagePin]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateMessagePin(self._session, self._host, self._interceptor) # type: ignore + @property def create_reaction( self, @@ -10005,6 +10561,14 @@ def delete_message( # In C++ this would require a dynamic_cast return self._DeleteMessage(self._session, self._host, self._interceptor) # type: ignore + @property + def delete_message_pin( + self, + ) -> Callable[[message_pin.DeleteMessagePinRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteMessagePin(self._session, self._host, self._interceptor) # type: ignore + @property def delete_reaction( self, @@ -10148,6 +10712,16 @@ def list_memberships( # In C++ this would require a dynamic_cast return self._ListMemberships(self._session, self._host, self._interceptor) # type: ignore + @property + def list_message_pins( + self, + ) -> Callable[ + [message_pin.ListMessagePinsRequest], message_pin.ListMessagePinsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListMessagePins(self._session, self._host, self._interceptor) # type: ignore + @property def list_messages( self, diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest_base.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest_base.py index bf8ada856450..576676a38105 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest_base.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest_base.py @@ -26,6 +26,7 @@ availability, membership, message, + message_pin, reaction, section, space, @@ -38,6 +39,7 @@ from google.apps.chat_v1.types import availability as gc_availability from google.apps.chat_v1.types import membership as gc_membership from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import message_pin as gc_message_pin from google.apps.chat_v1.types import reaction as gc_reaction from google.apps.chat_v1.types import section as gc_section from google.apps.chat_v1.types import space as gc_space @@ -179,6 +181,23 @@ def _get_http_options(): ] return http_options + class _BaseCreateMessagePin: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=spaces/*}/messagePins", + "body": "message_pin", + }, + ] + return http_options + class _BaseCreateReaction: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -278,6 +297,22 @@ def _get_http_options(): ] return http_options + class _BaseDeleteMessagePin: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=spaces/*/messagePins/*}", + }, + ] + return http_options + class _BaseDeleteReaction: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -548,6 +583,22 @@ def _get_http_options(): ] return http_options + class _BaseListMessagePins: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=spaces/*}/messagePins", + }, + ] + return http_options + class _BaseListMessages: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/__init__.py b/packages/google-apps-chat/google/apps/chat_v1/types/__init__.py index 2513d2035262..576b387b98a1 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/types/__init__.py +++ b/packages/google-apps-chat/google/apps/chat_v1/types/__init__.py @@ -28,6 +28,9 @@ SlashCommandMetadata, UserMentionMetadata, ) +from .app_command_metadata import ( + AppCommandMetadata, +) from .attachment import ( Attachment, AttachmentDataRef, @@ -119,6 +122,13 @@ Thread, UpdateMessageRequest, ) +from .message_pin import ( + CreateMessagePinRequest, + DeleteMessagePinRequest, + ListMessagePinsRequest, + ListMessagePinsResponse, + MessagePin, +) from .reaction import ( CreateCustomEmojiRequest, CreateReactionRequest, @@ -211,6 +221,7 @@ "SlashCommandMetadata", "UserMentionMetadata", "AnnotationType", + "AppCommandMetadata", "Attachment", "AttachmentDataRef", "DriveDataRef", @@ -278,6 +289,11 @@ "SearchMessagesResponse", "Thread", "UpdateMessageRequest", + "CreateMessagePinRequest", + "DeleteMessagePinRequest", + "ListMessagePinsRequest", + "ListMessagePinsResponse", + "MessagePin", "CreateCustomEmojiRequest", "CreateReactionRequest", "CustomEmoji", diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/annotation.py b/packages/google-apps-chat/google/apps/chat_v1/types/annotation.py index 1ba4b0901155..d426069ae5f2 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/types/annotation.py +++ b/packages/google-apps-chat/google/apps/chat_v1/types/annotation.py @@ -63,10 +63,10 @@ class AnnotationType(proto.Enum): class Annotation(proto.Message): - r"""Output only. Annotations can be associated with the plain-text body - of the message or with chips that link to Google Workspace resources - like Google Docs or Sheets with ``start_index`` and ``length`` of 0. - To add basic formatting to a text message, see `Format text + r"""Annotations can be associated with the plain-text body of the + message or with chips that link to Google Workspace resources like + Google Docs or Sheets with ``start_index`` and ``length`` of 0. To + add basic formatting to a text message, see `Format text messages `__. Example plain-text message body: diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/app_command_metadata.py b/packages/google-apps-chat/google/apps/chat_v1/types/app_command_metadata.py new file mode 100644 index 000000000000..acf40ce7fa03 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/app_command_metadata.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.chat.v1", + manifest={ + "AppCommandMetadata", + }, +) + + +class AppCommandMetadata(proto.Message): + r"""Metadata about a `Chat app + command `__. + + Attributes: + app_command_id (int): + The ID for the command specified in the Chat + API configuration. + app_command_type (google.apps.chat_v1.types.AppCommandMetadata.AppCommandType): + The type of Chat app command. + """ + + class AppCommandType(proto.Enum): + r"""The type of Chat app command. For details, see `Types of Chat app + commands `__. + + Values: + APP_COMMAND_TYPE_UNSPECIFIED (0): + Default value. Unspecified. + SLASH_COMMAND (1): + A slash command. The user sends the command + in a Chat message. + QUICK_COMMAND (3): + A quick command. The user selects the command + from the Chat menu in the message reply area. + MESSAGE_ACTION (4): + A message action. The user selects the + command from the message context menu in Chat. + """ + + APP_COMMAND_TYPE_UNSPECIFIED = 0 + SLASH_COMMAND = 1 + QUICK_COMMAND = 3 + MESSAGE_ACTION = 4 + + app_command_id: int = proto.Field( + proto.INT32, + number=1, + ) + app_command_type: AppCommandType = proto.Field( + proto.ENUM, + number=2, + enum=AppCommandType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/message.py b/packages/google-apps-chat/google/apps/chat_v1/types/message.py index a1b87409bf2d..c394ffbdd8a0 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/types/message.py +++ b/packages/google-apps-chat/google/apps/chat_v1/types/message.py @@ -921,10 +921,26 @@ class CreateMessageRequest(proto.Message): usage, see `Start or reply to a message thread `__. request_id (str): - Optional. A unique request ID for this - message. Specifying an existing request ID - returns the message created with that ID instead - of creating a new message. + Optional. A unique ID for this request. A random UUID is + recommended. Specifying a request ID makes the request + idempotent, which ensures that multiple identical requests + with the same request ID result in only a single message + being created. Subsequent requests with the same request ID + return the existing message and do not update the message, + even if the requested details differ from the current state. + + To use this field effectively: + + - Ensure that subsequent requests are identical and use the + same authentication credentials as the original request. + - If a message was already created with the provided request + ID, the request returns that message. Note that the + returned message might not be fully populated; the API + echoes the message in your request with the + system-assigned resource names populated. To retrieve the + latest metadata for the message, call ``GetMessage``. + - Reusing an existing request ID with a different + authenticated user results in an error. message_reply_option (google.apps.chat_v1.types.CreateMessageRequest.MessageReplyOption): Optional. Specifies whether a message starts a thread or replies to one. Only supported in named spaces. @@ -1354,6 +1370,11 @@ class SearchMessagesRequest(proto.Message): matches. For example, ``space.display_name:Project`` searches for messages in the top five spaces that contain the word "Project" in their display names. + - ``space.space_type``: The type of the space. Only supports + ``=``. For example, ``space.space_type="DIRECT_MESSAGE"`` + returns only messages from direct messages. The possible + values are ``DIRECT_MESSAGE``, ``GROUP_CHAT``, and + ``SPACE``. - ``attachment``: Supports the operator ``:*`` (has any) to check for the presence of attachments. If ``attachment:*`` is specified, only messages that have at least one @@ -1378,9 +1399,9 @@ class SearchMessagesRequest(proto.Message): - ``is_unread()``: Filters out messages that have been read by the calling user. - Using the ``space.display_name`` filter requires that the - calling credentials include one of the following - `authorization + Using the ``space.display_name`` or the ``space.space_type`` + filters requires that the calling credentials include one of + the following `authorization scopes `__: - ``https://www.googleapis.com/auth/chat.spaces.readonly`` @@ -1422,6 +1443,9 @@ class SearchMessagesRequest(proto.Message): ``space.display_name:Project OR space.display_name:Tasks`` returns messages that are in spaces with display names containing either ``Project`` or ``Tasks`` or both. + - ``space.space_type`` supports only the ``OR`` operator, + for example: + ``space.space_type = "DIRECT_MESSAGE" OR space.space_type = "GROUP_CHAT"``. - ``annotations.user_mentions.user.name`` supports the operators ``AND`` and ``OR``, but not a mix of both. For example: diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/message_pin.py b/packages/google-apps-chat/google/apps/chat_v1/types/message_pin.py new file mode 100644 index 000000000000..c7b98f07cc8f --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/message_pin.py @@ -0,0 +1,163 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.chat.v1", + manifest={ + "MessagePin", + "ListMessagePinsRequest", + "ListMessagePinsResponse", + "CreateMessagePinRequest", + "DeleteMessagePinRequest", + }, +) + + +class MessagePin(proto.Message): + r"""A pin on a Chat message. For more information see `Pin a + message `__. + + Attributes: + name (str): + Identifier. The resource name of the message pin. Format: + ``spaces/{space}/messagePins/{message_pin}`` The resource ID + component matches the resource ID component of the message. + For example, a message with ``spaces/AAA/messages/bbb.ccc`` + corresponds to the message pin with the resource name + ``spaces/AAA/messagePins/bbb.ccc``. + message (str): + Required. Immutable. The resource name of the message that + is pinned. Format: ``spaces/{space}/messages/{message}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + message: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListMessagePinsRequest(proto.Message): + r"""Request message for listing message pins. + + Attributes: + parent (str): + Required. The parent space which owns the collection of + pinned items Format: ``spaces/{space}`` + page_size (int): + Optional. The maximum number of message pins returned. The + service might return fewer messages than this value. The + maximum value is 100. If you use a value more than 100, it's + automatically changed to 100. If unspecified, at most 100 + message pins will be returned. Negative values return an + ``INVALID_ARGUMENT`` error. + page_token (str): + Optional. A page token received from a + previous list message pins call. Provide this + parameter to retrieve the subsequent page. + + When paginating, all other parameters provided + should match the call that provided the page + token. Passing different values to the other + parameters might lead to unexpected results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListMessagePinsResponse(proto.Message): + r"""Response message for listing message pins. + + Attributes: + message_pins (MutableSequence[google.apps.chat_v1.types.MessagePin]): + The pinned messages from the specified space. + next_page_token (str): + You can send a token as ``pageToken`` to retrieve the next + page of results. If empty, there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + message_pins: MutableSequence["MessagePin"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="MessagePin", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateMessagePinRequest(proto.Message): + r"""Request message for creating a message pin. + + Attributes: + parent (str): + Required. The parent space in which to create + the message pin. Format: spaces/{space} + message_pin (google.apps.chat_v1.types.MessagePin): + Required. The MessagePin to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + message_pin: "MessagePin" = proto.Field( + proto.MESSAGE, + number=2, + message="MessagePin", + ) + + +class DeleteMessagePinRequest(proto.Message): + r"""Request message for deleting a message pin. + + Attributes: + name (str): + Required. The resource name of the message pin to remove. + Format: spaces/{space}/messagePins/{message_pin} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/space.py b/packages/google-apps-chat/google/apps/chat_v1/types/space.py index 03b15106b8f9..7a6bdfdaae64 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/types/space.py +++ b/packages/google-apps-chat/google/apps/chat_v1/types/space.py @@ -494,6 +494,18 @@ class AccessPermissionSettings(proto.Message): join_space_setting (google.apps.chat_v1.types.Space.AccessPermissionSetting): Optional. Access permission setting for joining the space. + view_space_membership_setting (google.apps.chat_v1.types.Space.AccessPermissionSetting): + Optional. Access permission setting for viewing space + membership. Must be specified together with + ``PermissionSettings.view_space_membership`` in the update + mask and request body when updating who can view space + membership. When granting view access to a target audience, + you must also grant + ``PermissionSettings.view_space_membership`` to all members + in the same request. To remove an existing target audience + (for example, to restrict view access to space managers or + assistant managers only), specify an empty + ``AccessPermissionSetting`` (with no ``principals``). """ discover_space_setting: "Space.AccessPermissionSetting" = proto.Field( @@ -506,6 +518,11 @@ class AccessPermissionSettings(proto.Message): number=2, message="Space.AccessPermissionSetting", ) + view_space_membership_setting: "Space.AccessPermissionSetting" = proto.Field( + proto.MESSAGE, + number=3, + message="Space.AccessPermissionSetting", + ) class AccessPermissionSetting(proto.Message): r"""An access permission setting. @@ -592,6 +609,21 @@ class PermissionSettings(proto.Message): a space. This field is a member of `oneof`_ ``_reply_messages``. + view_space_membership (google.apps.chat_v1.types.Space.PermissionSetting): + Optional. Setting for viewing space membership. Must be + specified together with + ``AccessPermissionSettings.view_space_membership_setting`` + in the update mask and request body when updating who can + view space membership. When restricting view access to + specific roles (for example, space managers or assistant + managers only), specify the desired role permissions here + and provide an empty + ``AccessPermissionSettings.view_space_membership_setting`` + in the same request. If a target audience is configured in + ``AccessPermissionSettings.view_space_membership_setting``, + this setting must be granted to all members. + + This field is a member of `oneof`_ ``_view_space_membership``. """ manage_members_and_groups: "Space.PermissionSetting" = proto.Field( @@ -642,6 +674,12 @@ class PermissionSettings(proto.Message): optional=True, message="Space.PermissionSetting", ) + view_space_membership: "Space.PermissionSetting" = proto.Field( + proto.MESSAGE, + number=9, + optional=True, + message="Space.PermissionSetting", + ) class PermissionSetting(proto.Message): r"""Represents a space permission setting. @@ -799,14 +837,26 @@ class CreateSpaceRequest(proto.Message): The space ``name`` is assigned on the server so anything specified in this field will be ignored. request_id (str): - Optional. A unique identifier for this - request. A random UUID is recommended. - Specifying an existing request ID returns the - space created with that ID instead of creating a - new space. - Specifying an existing request ID from the same - Chat app with a different authenticated user - returns an error. + Optional. A unique ID for this request. A random UUID is + recommended. Specifying a request ID makes the request + idempotent, which ensures that multiple identical requests + with the same request ID result in only a single space being + created. Subsequent requests with the same request ID return + the existing space and do not update the space, even if the + requested details differ from the current state. + + To use this field effectively: + + - Ensure that subsequent requests are identical and use the + same authentication credentials as the original request. + - If a space was already created with the provided request + ID, the request returns that space. Note that the returned + space might not be fully populated; the API echoes the + space in your request with the system-assigned resource + name populated. To retrieve the latest metadata for the + space, call ``GetSpace``. + - Reusing an existing request ID with a different + authenticated user results in an error. """ space: "Space" = proto.Field( @@ -1151,6 +1201,7 @@ class UpdateSpaceRequest(proto.Message): - ``access_settings.access_permission_settings.discoverSpaceSetting`` - ``access_settings.access_permission_settings.joinSpaceSetting`` + - ``access_settings.access_permission_settings.viewSpaceMembershipSetting`` ``permission_settings``: Supports changing the `permission settings `__ @@ -1166,6 +1217,7 @@ class UpdateSpaceRequest(proto.Message): - ``permission_settings.manageApps`` - ``permission_settings.manageWebhooks`` - ``permission_settings.replyMessages`` + - ``permission_settings.viewSpaceMembership`` use_admin_access (bool): Optional. When ``true``, the method runs using the user's Google Workspace administrator privileges. @@ -1213,14 +1265,15 @@ class SearchSpacesRequest(proto.Message): ``chat.admin.spaces`` `OAuth 2.0 scope `__. page_size (int): - The maximum number of spaces to return. The - service may return fewer than this value. + The maximum number of spaces to return. The service may + return fewer than this value. If unspecified, at most 100 spaces are returned. - The maximum value is 1000. If you use a value - more than 1000, it's automatically changed to - 1000. + The maximum value is 1000 when ``useAdminAccess`` is set to + ``true``. Otherwise, the maximum value is 100. If you use a + value more than the maximum value, it's automatically + changed to the maximum value. page_token (str): A token, received from the previous search spaces call. Provide this parameter to retrieve @@ -1334,6 +1387,11 @@ class SearchSpacesRequest(proto.Message): (external_user_allowed = "true" AND display_name:"Hello" AND space_type = "SPACE") + + The maximum query length is 1,000 characters. + + Invalid queries are rejected by the server with an + ``INVALID_ARGUMENT`` error. order_by (str): Optional. How the list of spaces is ordered. @@ -1406,13 +1464,16 @@ class SearchSpacesResponse(proto.Message): only when ``useAdminAccess`` is set to ``true`` and deprecated in favor of the new ``results`` field. next_page_token (str): - A token that can be used to retrieve the next - page. If this field is empty, there are no - subsequent pages. + A token that can be used to retrieve the next page. If this + field is empty, there are no subsequent pages. + + Only populated when ``useAdminAccess`` is set to ``true``. total_size (int): - The total number of spaces that match the - query, across all pages. If the result is over - 10,000 spaces, this value is an estimate. + The total number of spaces that match the query, across all + pages. If the result is over 10,000 spaces, this value is an + estimate. + + Only populated when ``useAdminAccess`` is set to ``true``. results (MutableSequence[google.apps.chat_v1.types.SearchSpacesResponse.SearchSpaceResult]): Output only. The list of search results that matched the query. diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/space_setup.py b/packages/google-apps-chat/google/apps/chat_v1/types/space_setup.py index 2af6c048a7f1..c8afcd6afb99 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/types/space_setup.py +++ b/packages/google-apps-chat/google/apps/chat_v1/types/space_setup.py @@ -60,14 +60,26 @@ class SetUpSpaceRequest(proto.Message): If a ``DIRECT_MESSAGE`` space already exists, that space is returned instead of creating a new space. request_id (str): - Optional. A unique identifier for this - request. A random UUID is recommended. - Specifying an existing request ID returns the - space created with that ID instead of creating a - new space. - Specifying an existing request ID from the same - Chat app with a different authenticated user - returns an error. + Optional. A unique ID for this request. A random UUID is + recommended. Specifying a request ID makes the request + idempotent, which ensures that multiple identical requests + with the same request ID result in only a single space being + created. Subsequent requests with the same request ID return + the existing space and do not update the space, even if the + requested details differ from the current state. + + To use this field effectively: + + - Ensure that subsequent requests are identical and use the + same authentication credentials as the original request. + - If a space was already created with the provided request + ID, the request returns that space. Note that the returned + space might not be fully populated; the API echoes the + space in your request with the system-assigned resource + name populated. To retrieve the latest metadata for the + space, call ``GetSpace``. + - Reusing an existing request ID with a different + authenticated user results in an error. memberships (MutableSequence[google.apps.chat_v1.types.Membership]): Optional. The Google Chat users or groups to invite to join the space. Omit the calling user, as they are added diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_message_pin_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_message_pin_async.py new file mode 100644 index 000000000000..f38708b67047 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_message_pin_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMessagePin +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_CreateMessagePin_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_create_message_pin(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + message_pin = chat_v1.MessagePin() + message_pin.message = "message_value" + + request = chat_v1.CreateMessagePinRequest( + parent="parent_value", + message_pin=message_pin, + ) + + # Make the request + response = await client.create_message_pin(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_CreateMessagePin_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_message_pin_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_message_pin_sync.py new file mode 100644 index 000000000000..d6cc5573b753 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_message_pin_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMessagePin +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_CreateMessagePin_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_create_message_pin(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + message_pin = chat_v1.MessagePin() + message_pin.message = "message_value" + + request = chat_v1.CreateMessagePinRequest( + parent="parent_value", + message_pin=message_pin, + ) + + # Make the request + response = client.create_message_pin(request=request) + + # Handle the response + print(response) + + +# [END chat_v1_generated_ChatService_CreateMessagePin_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_message_pin_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_message_pin_async.py new file mode 100644 index 000000000000..7b2ad70403b1 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_message_pin_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteMessagePin +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteMessagePin_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_delete_message_pin(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMessagePinRequest( + name="name_value", + ) + + # Make the request + await client.delete_message_pin(request=request) + + +# [END chat_v1_generated_ChatService_DeleteMessagePin_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_message_pin_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_message_pin_sync.py new file mode 100644 index 000000000000..d8feae941dfc --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_message_pin_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteMessagePin +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteMessagePin_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_delete_message_pin(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMessagePinRequest( + name="name_value", + ) + + # Make the request + client.delete_message_pin(request=request) + + +# [END chat_v1_generated_ChatService_DeleteMessagePin_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_message_pins_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_message_pins_async.py new file mode 100644 index 000000000000..3b5f5ad867bc --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_message_pins_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMessagePins +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_ListMessagePins_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +async def sample_list_message_pins(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListMessagePinsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_pins(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END chat_v1_generated_ChatService_ListMessagePins_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_message_pins_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_message_pins_sync.py new file mode 100644 index 000000000000..ff062ca1d71a --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_message_pins_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMessagePins +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-apps-chat + + +# [START chat_v1_generated_ChatService_ListMessagePins_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.apps import chat_v1 + + +def sample_list_message_pins(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListMessagePinsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_message_pins(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END chat_v1_generated_ChatService_ListMessagePins_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/snippet_metadata_google.chat.v1.json b/packages/google-apps-chat/samples/generated_samples/snippet_metadata_google.chat.v1.json index 3b1e7d89382f..4dcef1ec8b0a 100644 --- a/packages/google-apps-chat/samples/generated_samples/snippet_metadata_google.chat.v1.json +++ b/packages/google-apps-chat/samples/generated_samples/snippet_metadata_google.chat.v1.json @@ -494,6 +494,175 @@ ], "title": "chat_v1_generated_chat_service_create_membership_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.create_message_pin", + "method": { + "fullName": "google.chat.v1.ChatService.CreateMessagePin", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateMessagePin" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateMessagePinRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "message_pin", + "type": "google.apps.chat_v1.types.MessagePin" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.chat_v1.types.MessagePin", + "shortName": "create_message_pin" + }, + "description": "Sample for CreateMessagePin", + "file": "chat_v1_generated_chat_service_create_message_pin_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateMessagePin_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_create_message_pin_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.create_message_pin", + "method": { + "fullName": "google.chat.v1.ChatService.CreateMessagePin", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateMessagePin" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateMessagePinRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "message_pin", + "type": "google.apps.chat_v1.types.MessagePin" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.chat_v1.types.MessagePin", + "shortName": "create_message_pin" + }, + "description": "Sample for CreateMessagePin", + "file": "chat_v1_generated_chat_service_create_message_pin_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateMessagePin_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_create_message_pin_sync.py" + }, { "canonical": true, "clientMethod": { @@ -1486,6 +1655,161 @@ ], "title": "chat_v1_generated_chat_service_delete_membership_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.delete_message_pin", + "method": { + "fullName": "google.chat.v1.ChatService.DeleteMessagePin", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "DeleteMessagePin" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.DeleteMessagePinRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_message_pin" + }, + "description": "Sample for DeleteMessagePin", + "file": "chat_v1_generated_chat_service_delete_message_pin_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_DeleteMessagePin_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_delete_message_pin_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.delete_message_pin", + "method": { + "fullName": "google.chat.v1.ChatService.DeleteMessagePin", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "DeleteMessagePin" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.DeleteMessagePinRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_message_pin" + }, + "description": "Sample for DeleteMessagePin", + "file": "chat_v1_generated_chat_service_delete_message_pin_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_DeleteMessagePin_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_delete_message_pin_sync.py" + }, { "canonical": true, "clientMethod": { @@ -4336,6 +4660,167 @@ ], "title": "chat_v1_generated_chat_service_list_memberships_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.list_message_pins", + "method": { + "fullName": "google.chat.v1.ChatService.ListMessagePins", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListMessagePins" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListMessagePinsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListMessagePinsAsyncPager", + "shortName": "list_message_pins" + }, + "description": "Sample for ListMessagePins", + "file": "chat_v1_generated_chat_service_list_message_pins_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListMessagePins_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": "chat_v1_generated_chat_service_list_message_pins_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.list_message_pins", + "method": { + "fullName": "google.chat.v1.ChatService.ListMessagePins", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListMessagePins" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListMessagePinsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListMessagePinsPager", + "shortName": "list_message_pins" + }, + "description": "Sample for ListMessagePins", + "file": "chat_v1_generated_chat_service_list_message_pins_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListMessagePins_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": "chat_v1_generated_chat_service_list_message_pins_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py b/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py index 3c1c4da1bfd9..1b84cdfca864 100644 --- a/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py +++ b/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py @@ -80,6 +80,7 @@ matched_url, membership, message, + message_pin, reaction, section, slash_command, @@ -95,6 +96,7 @@ from google.apps.chat_v1.types import availability as gc_availability from google.apps.chat_v1.types import membership as gc_membership from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import message_pin as gc_message_pin from google.apps.chat_v1.types import reaction as gc_reaction from google.apps.chat_v1.types import section as gc_section from google.apps.chat_v1.types import space as gc_space @@ -1102,6 +1104,8 @@ def test_chat_service_client_create_channel_credentials_file( "https://www.googleapis.com/auth/chat.messages.readonly", "https://www.googleapis.com/auth/chat.spaces", "https://www.googleapis.com/auth/chat.spaces.create", + "https://www.googleapis.com/auth/chat.spaces.pins", + "https://www.googleapis.com/auth/chat.spaces.pins.readonly", "https://www.googleapis.com/auth/chat.spaces.readonly", "https://www.googleapis.com/auth/chat.users.availability", "https://www.googleapis.com/auth/chat.users.availability.readonly", @@ -10528,11 +10532,11 @@ async def test_delete_reaction_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - reaction.CreateCustomEmojiRequest(), + message_pin.ListMessagePinsRequest(), {}, ], ) -def test_create_custom_emoji(request_type, transport: str = "grpc"): +def test_list_message_pins(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10544,32 +10548,26 @@ def test_create_custom_emoji(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_emoji), "__call__" + type(client.transport.list_message_pins), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = reaction.CustomEmoji( - name="name_value", - uid="uid_value", - emoji_name="emoji_name_value", - temporary_image_uri="temporary_image_uri_value", + call.return_value = message_pin.ListMessagePinsResponse( + next_page_token="next_page_token_value", ) - response = client.create_custom_emoji(request) + response = client.list_message_pins(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = reaction.CreateCustomEmojiRequest() + request = message_pin.ListMessagePinsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, reaction.CustomEmoji) - assert response.name == "name_value" - assert response.uid == "uid_value" - assert response.emoji_name == "emoji_name_value" - assert response.temporary_image_uri == "temporary_image_uri_value" + assert isinstance(response, pagers.ListMessagePinsPager) + assert response.next_page_token == "next_page_token_value" -def test_create_custom_emoji_non_empty_request_with_auto_populated_field(): +def test_list_message_pins_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -10580,23 +10578,29 @@ def test_create_custom_emoji_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = reaction.CreateCustomEmojiRequest() + request = message_pin.ListMessagePinsRequest( + parent="parent_value", + page_token="page_token_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_emoji), "__call__" + type(client.transport.list_message_pins), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_custom_emoji(request=request) + client.list_message_pins(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = reaction.CreateCustomEmojiRequest() + request_msg = message_pin.ListMessagePinsRequest( + parent="parent_value", + page_token="page_token_value", + ) assert args[0] == request_msg -def test_create_custom_emoji_use_cached_wrapped_rpc(): +def test_list_message_pins_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -10610,25 +10614,23 @@ def test_create_custom_emoji_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_custom_emoji in client._transport._wrapped_methods - ) + assert client._transport.list_message_pins in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_custom_emoji] = ( + client._transport._wrapped_methods[client._transport.list_message_pins] = ( mock_rpc ) request = {} - client.create_custom_emoji(request) + client.list_message_pins(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_custom_emoji(request) + client.list_message_pins(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10636,7 +10638,7 @@ def test_create_custom_emoji_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_custom_emoji_async_use_cached_wrapped_rpc( +async def test_list_message_pins_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -10653,7 +10655,7 @@ async def test_create_custom_emoji_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_custom_emoji + client._client._transport.list_message_pins in client._client._transport._wrapped_methods ) @@ -10661,16 +10663,16 @@ async def test_create_custom_emoji_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_custom_emoji + client._client._transport.list_message_pins ] = mock_rpc request = {} - await client.create_custom_emoji(request) + await client.list_message_pins(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.create_custom_emoji(request) + await client.list_message_pins(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10681,11 +10683,11 @@ async def test_create_custom_emoji_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - reaction.CreateCustomEmojiRequest(), + message_pin.ListMessagePinsRequest(), {}, ], ) -async def test_create_custom_emoji_async(request_type, transport: str = "grpc_asyncio"): +async def test_list_message_pins_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -10697,60 +10699,119 @@ async def test_create_custom_emoji_async(request_type, transport: str = "grpc_as # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_emoji), "__call__" + type(client.transport.list_message_pins), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - reaction.CustomEmoji( - name="name_value", - uid="uid_value", - emoji_name="emoji_name_value", - temporary_image_uri="temporary_image_uri_value", + message_pin.ListMessagePinsResponse( + next_page_token="next_page_token_value", ) ) - response = await client.create_custom_emoji(request) + response = await client.list_message_pins(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = reaction.CreateCustomEmojiRequest() + request = message_pin.ListMessagePinsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, reaction.CustomEmoji) - assert response.name == "name_value" - assert response.uid == "uid_value" - assert response.emoji_name == "emoji_name_value" - assert response.temporary_image_uri == "temporary_image_uri_value" + assert isinstance(response, pagers.ListMessagePinsAsyncPager) + assert response.next_page_token == "next_page_token_value" -def test_create_custom_emoji_flattened(): +def test_list_message_pins_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = message_pin.ListMessagePinsRequest() + + request.parent = "parent_value" + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_emoji), "__call__" + type(client.transport.list_message_pins), "__call__" + ) as call: + call.return_value = message_pin.ListMessagePinsResponse() + client.list_message_pins(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_message_pins_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = message_pin.ListMessagePinsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_pins), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + message_pin.ListMessagePinsResponse() + ) + await client.list_message_pins(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_message_pins_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_pins), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = reaction.CustomEmoji() + call.return_value = message_pin.ListMessagePinsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_custom_emoji( - custom_emoji=reaction.CustomEmoji(name="name_value"), + client.list_message_pins( + 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].custom_emoji - mock_val = reaction.CustomEmoji(name="name_value") + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_create_custom_emoji_flattened_error(): +def test_list_message_pins_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -10758,45 +10819,45 @@ def test_create_custom_emoji_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_custom_emoji( - reaction.CreateCustomEmojiRequest(), - custom_emoji=reaction.CustomEmoji(name="name_value"), + client.list_message_pins( + message_pin.ListMessagePinsRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_create_custom_emoji_flattened_async(): +async def test_list_message_pins_flattened_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_emoji), "__call__" + type(client.transport.list_message_pins), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = reaction.CustomEmoji() + call.return_value = message_pin.ListMessagePinsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - reaction.CustomEmoji() + message_pin.ListMessagePinsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_custom_emoji( - custom_emoji=reaction.CustomEmoji(name="name_value"), + response = await client.list_message_pins( + 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].custom_emoji - mock_val = reaction.CustomEmoji(name="name_value") + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_custom_emoji_flattened_error_async(): +async def test_list_message_pins_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -10804,20 +10865,223 @@ async def test_create_custom_emoji_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_custom_emoji( - reaction.CreateCustomEmojiRequest(), - custom_emoji=reaction.CustomEmoji(name="name_value"), + await client.list_message_pins( + message_pin.ListMessagePinsRequest(), + parent="parent_value", + ) + + +def test_list_message_pins_pager(transport_name: str = "grpc"): + client = ChatServiceClient( + 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_message_pins), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + message_pin.ListMessagePinsResponse( + message_pins=[ + message_pin.MessagePin(), + message_pin.MessagePin(), + message_pin.MessagePin(), + ], + next_page_token="abc", + ), + message_pin.ListMessagePinsResponse( + message_pins=[], + next_page_token="def", + ), + message_pin.ListMessagePinsResponse( + message_pins=[ + message_pin.MessagePin(), + ], + next_page_token="ghi", + ), + message_pin.ListMessagePinsResponse( + message_pins=[ + message_pin.MessagePin(), + message_pin.MessagePin(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_message_pins(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, message_pin.MessagePin) for i in results) + + +def test_list_message_pins_pages(transport_name: str = "grpc"): + client = ChatServiceClient( + 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_message_pins), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + message_pin.ListMessagePinsResponse( + message_pins=[ + message_pin.MessagePin(), + message_pin.MessagePin(), + message_pin.MessagePin(), + ], + next_page_token="abc", + ), + message_pin.ListMessagePinsResponse( + message_pins=[], + next_page_token="def", + ), + message_pin.ListMessagePinsResponse( + message_pins=[ + message_pin.MessagePin(), + ], + next_page_token="ghi", + ), + message_pin.ListMessagePinsResponse( + message_pins=[ + message_pin.MessagePin(), + message_pin.MessagePin(), + ], + ), + RuntimeError, + ) + pages = list(client.list_message_pins(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_message_pins_async_pager(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_pins), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + message_pin.ListMessagePinsResponse( + message_pins=[ + message_pin.MessagePin(), + message_pin.MessagePin(), + message_pin.MessagePin(), + ], + next_page_token="abc", + ), + message_pin.ListMessagePinsResponse( + message_pins=[], + next_page_token="def", + ), + message_pin.ListMessagePinsResponse( + message_pins=[ + message_pin.MessagePin(), + ], + next_page_token="ghi", + ), + message_pin.ListMessagePinsResponse( + message_pins=[ + message_pin.MessagePin(), + message_pin.MessagePin(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_message_pins( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, message_pin.MessagePin) for i in responses) + + +@pytest.mark.asyncio +async def test_list_message_pins_async_pages(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_message_pins), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + message_pin.ListMessagePinsResponse( + message_pins=[ + message_pin.MessagePin(), + message_pin.MessagePin(), + message_pin.MessagePin(), + ], + next_page_token="abc", + ), + message_pin.ListMessagePinsResponse( + message_pins=[], + next_page_token="def", + ), + message_pin.ListMessagePinsResponse( + message_pins=[ + message_pin.MessagePin(), + ], + next_page_token="ghi", + ), + message_pin.ListMessagePinsResponse( + message_pins=[ + message_pin.MessagePin(), + message_pin.MessagePin(), + ], + ), + RuntimeError, ) + pages = [] + async for page_ in (await client.list_message_pins(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", [ - reaction.GetCustomEmojiRequest(), + gc_message_pin.CreateMessagePinRequest(), {}, ], ) -def test_get_custom_emoji(request_type, transport: str = "grpc"): +def test_create_message_pin(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10828,31 +11092,29 @@ def test_get_custom_emoji(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_custom_emoji), "__call__") as call: + with mock.patch.object( + type(client.transport.create_message_pin), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = reaction.CustomEmoji( + call.return_value = gc_message_pin.MessagePin( name="name_value", - uid="uid_value", - emoji_name="emoji_name_value", - temporary_image_uri="temporary_image_uri_value", + message="message_value", ) - response = client.get_custom_emoji(request) + response = client.create_message_pin(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = reaction.GetCustomEmojiRequest() + request = gc_message_pin.CreateMessagePinRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, reaction.CustomEmoji) + assert isinstance(response, gc_message_pin.MessagePin) assert response.name == "name_value" - assert response.uid == "uid_value" - assert response.emoji_name == "emoji_name_value" - assert response.temporary_image_uri == "temporary_image_uri_value" + assert response.message == "message_value" -def test_get_custom_emoji_non_empty_request_with_auto_populated_field(): +def test_create_message_pin_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -10863,25 +11125,27 @@ def test_get_custom_emoji_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = reaction.GetCustomEmojiRequest( - name="name_value", + request = gc_message_pin.CreateMessagePinRequest( + parent="parent_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_custom_emoji), "__call__") as call: + with mock.patch.object( + type(client.transport.create_message_pin), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_custom_emoji(request=request) + client.create_message_pin(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = reaction.GetCustomEmojiRequest( - name="name_value", + request_msg = gc_message_pin.CreateMessagePinRequest( + parent="parent_value", ) assert args[0] == request_msg -def test_get_custom_emoji_use_cached_wrapped_rpc(): +def test_create_message_pin_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -10895,23 +11159,25 @@ def test_get_custom_emoji_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_custom_emoji in client._transport._wrapped_methods + assert ( + client._transport.create_message_pin in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_custom_emoji] = ( + client._transport._wrapped_methods[client._transport.create_message_pin] = ( mock_rpc ) request = {} - client.get_custom_emoji(request) + client.create_message_pin(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_custom_emoji(request) + client.create_message_pin(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10919,7 +11185,7 @@ def test_get_custom_emoji_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_custom_emoji_async_use_cached_wrapped_rpc( +async def test_create_message_pin_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -10936,7 +11202,7 @@ async def test_get_custom_emoji_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_custom_emoji + client._client._transport.create_message_pin in client._client._transport._wrapped_methods ) @@ -10944,16 +11210,16 @@ async def test_get_custom_emoji_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_custom_emoji + client._client._transport.create_message_pin ] = mock_rpc request = {} - await client.get_custom_emoji(request) + await client.create_message_pin(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_custom_emoji(request) + await client.create_message_pin(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10964,11 +11230,11 @@ async def test_get_custom_emoji_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - reaction.GetCustomEmojiRequest(), + gc_message_pin.CreateMessagePinRequest(), {}, ], ) -async def test_get_custom_emoji_async(request_type, transport: str = "grpc_asyncio"): +async def test_create_message_pin_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -10979,47 +11245,47 @@ async def test_get_custom_emoji_async(request_type, transport: str = "grpc_async request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_custom_emoji), "__call__") as call: + with mock.patch.object( + type(client.transport.create_message_pin), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - reaction.CustomEmoji( + gc_message_pin.MessagePin( name="name_value", - uid="uid_value", - emoji_name="emoji_name_value", - temporary_image_uri="temporary_image_uri_value", + message="message_value", ) ) - response = await client.get_custom_emoji(request) + response = await client.create_message_pin(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = reaction.GetCustomEmojiRequest() + request = gc_message_pin.CreateMessagePinRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, reaction.CustomEmoji) + assert isinstance(response, gc_message_pin.MessagePin) assert response.name == "name_value" - assert response.uid == "uid_value" - assert response.emoji_name == "emoji_name_value" - assert response.temporary_image_uri == "temporary_image_uri_value" + assert response.message == "message_value" -def test_get_custom_emoji_field_headers(): +def test_create_message_pin_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = reaction.GetCustomEmojiRequest() + request = gc_message_pin.CreateMessagePinRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_custom_emoji), "__call__") as call: - call.return_value = reaction.CustomEmoji() - client.get_custom_emoji(request) + with mock.patch.object( + type(client.transport.create_message_pin), "__call__" + ) as call: + call.return_value = gc_message_pin.MessagePin() + client.create_message_pin(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -11030,28 +11296,30 @@ def test_get_custom_emoji_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_custom_emoji_field_headers_async(): +async def test_create_message_pin_field_headers_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = reaction.GetCustomEmojiRequest() + request = gc_message_pin.CreateMessagePinRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_custom_emoji), "__call__") as call: + with mock.patch.object( + type(client.transport.create_message_pin), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - reaction.CustomEmoji() + gc_message_pin.MessagePin() ) - await client.get_custom_emoji(request) + await client.create_message_pin(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -11062,35 +11330,41 @@ async def test_get_custom_emoji_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_get_custom_emoji_flattened(): +def test_create_message_pin_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_custom_emoji), "__call__") as call: + with mock.patch.object( + type(client.transport.create_message_pin), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = reaction.CustomEmoji() + call.return_value = gc_message_pin.MessagePin() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_custom_emoji( - name="name_value", + client.create_message_pin( + parent="parent_value", + message_pin=gc_message_pin.MessagePin(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" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].message_pin + mock_val = gc_message_pin.MessagePin(name="name_value") assert arg == mock_val -def test_get_custom_emoji_flattened_error(): +def test_create_message_pin_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -11098,43 +11372,50 @@ def test_get_custom_emoji_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_custom_emoji( - reaction.GetCustomEmojiRequest(), - name="name_value", + client.create_message_pin( + gc_message_pin.CreateMessagePinRequest(), + parent="parent_value", + message_pin=gc_message_pin.MessagePin(name="name_value"), ) @pytest.mark.asyncio -async def test_get_custom_emoji_flattened_async(): +async def test_create_message_pin_flattened_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_custom_emoji), "__call__") as call: + with mock.patch.object( + type(client.transport.create_message_pin), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = reaction.CustomEmoji() + call.return_value = gc_message_pin.MessagePin() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - reaction.CustomEmoji() + gc_message_pin.MessagePin() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_custom_emoji( - name="name_value", + response = await client.create_message_pin( + parent="parent_value", + message_pin=gc_message_pin.MessagePin(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" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].message_pin + mock_val = gc_message_pin.MessagePin(name="name_value") assert arg == mock_val @pytest.mark.asyncio -async def test_get_custom_emoji_flattened_error_async(): +async def test_create_message_pin_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -11142,20 +11423,21 @@ async def test_get_custom_emoji_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_custom_emoji( - reaction.GetCustomEmojiRequest(), - name="name_value", + await client.create_message_pin( + gc_message_pin.CreateMessagePinRequest(), + parent="parent_value", + message_pin=gc_message_pin.MessagePin(name="name_value"), ) @pytest.mark.parametrize( "request_type", [ - reaction.ListCustomEmojisRequest(), + message_pin.DeleteMessagePinRequest(), {}, ], ) -def test_list_custom_emojis(request_type, transport: str = "grpc"): +def test_delete_message_pin(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11167,26 +11449,23 @@ def test_list_custom_emojis(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_emojis), "__call__" + type(client.transport.delete_message_pin), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = reaction.ListCustomEmojisResponse( - next_page_token="next_page_token_value", - ) - response = client.list_custom_emojis(request) + call.return_value = None + response = client.delete_message_pin(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = reaction.ListCustomEmojisRequest() + request = message_pin.DeleteMessagePinRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCustomEmojisPager) - assert response.next_page_token == "next_page_token_value" + assert response is None -def test_list_custom_emojis_non_empty_request_with_auto_populated_field(): +def test_delete_message_pin_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -11197,29 +11476,27 @@ def test_list_custom_emojis_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = reaction.ListCustomEmojisRequest( - page_token="page_token_value", - filter="filter_value", + request = message_pin.DeleteMessagePinRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_emojis), "__call__" + type(client.transport.delete_message_pin), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_custom_emojis(request=request) + client.delete_message_pin(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = reaction.ListCustomEmojisRequest( - page_token="page_token_value", - filter="filter_value", + request_msg = message_pin.DeleteMessagePinRequest( + name="name_value", ) assert args[0] == request_msg -def test_list_custom_emojis_use_cached_wrapped_rpc(): +def test_delete_message_pin_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -11234,7 +11511,7 @@ def test_list_custom_emojis_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_custom_emojis in client._transport._wrapped_methods + client._transport.delete_message_pin in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -11242,16 +11519,16 @@ def test_list_custom_emojis_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_custom_emojis] = ( + client._transport._wrapped_methods[client._transport.delete_message_pin] = ( mock_rpc ) request = {} - client.list_custom_emojis(request) + client.delete_message_pin(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_custom_emojis(request) + client.delete_message_pin(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11259,7 +11536,7 @@ def test_list_custom_emojis_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_custom_emojis_async_use_cached_wrapped_rpc( +async def test_delete_message_pin_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -11276,7 +11553,7 @@ async def test_list_custom_emojis_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_custom_emojis + client._client._transport.delete_message_pin in client._client._transport._wrapped_methods ) @@ -11284,16 +11561,16 @@ async def test_list_custom_emojis_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_custom_emojis + client._client._transport.delete_message_pin ] = mock_rpc request = {} - await client.list_custom_emojis(request) + await client.delete_message_pin(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_custom_emojis(request) + await client.delete_message_pin(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11304,11 +11581,11 @@ async def test_list_custom_emojis_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - reaction.ListCustomEmojisRequest(), + message_pin.DeleteMessagePinRequest(), {}, ], ) -async def test_list_custom_emojis_async(request_type, transport: str = "grpc_asyncio"): +async def test_delete_message_pin_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -11320,235 +11597,177 @@ async def test_list_custom_emojis_async(request_type, transport: str = "grpc_asy # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_emojis), "__call__" + type(client.transport.delete_message_pin), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - reaction.ListCustomEmojisResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_custom_emojis(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_message_pin(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = reaction.ListCustomEmojisRequest() + request = message_pin.DeleteMessagePinRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCustomEmojisAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert response is None -def test_list_custom_emojis_pager(transport_name: str = "grpc"): +def test_delete_message_pin_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = message_pin.DeleteMessagePinRequest() + + request.name = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_emojis), "__call__" + type(client.transport.delete_message_pin), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - reaction.ListCustomEmojisResponse( - custom_emojis=[ - reaction.CustomEmoji(), - reaction.CustomEmoji(), - reaction.CustomEmoji(), - ], - next_page_token="abc", - ), - reaction.ListCustomEmojisResponse( - custom_emojis=[], - next_page_token="def", - ), - reaction.ListCustomEmojisResponse( - custom_emojis=[ - reaction.CustomEmoji(), - ], - next_page_token="ghi", - ), - reaction.ListCustomEmojisResponse( - custom_emojis=[ - reaction.CustomEmoji(), - reaction.CustomEmoji(), - ], - ), - RuntimeError, - ) + call.return_value = None + client.delete_message_pin(request) - expected_metadata = () - retry = retries.Retry() - timeout = 5 - pager = client.list_custom_emojis(request={}, retry=retry, timeout=timeout) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, reaction.CustomEmoji) for i in results) +@pytest.mark.asyncio +async def test_delete_message_pin_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = message_pin.DeleteMessagePinRequest() -def test_list_custom_emojis_pages(transport_name: str = "grpc"): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_emojis), "__call__" + type(client.transport.delete_message_pin), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - reaction.ListCustomEmojisResponse( - custom_emojis=[ - reaction.CustomEmoji(), - reaction.CustomEmoji(), - reaction.CustomEmoji(), - ], - next_page_token="abc", - ), - reaction.ListCustomEmojisResponse( - custom_emojis=[], - next_page_token="def", - ), - reaction.ListCustomEmojisResponse( - custom_emojis=[ - reaction.CustomEmoji(), - ], - next_page_token="ghi", - ), - reaction.ListCustomEmojisResponse( - custom_emojis=[ - reaction.CustomEmoji(), - reaction.CustomEmoji(), - ], - ), - RuntimeError, - ) - pages = list(client.list_custom_emojis(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_message_pin(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request -@pytest.mark.asyncio -async def test_list_custom_emojis_async_pager(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), + # 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_message_pin_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_emojis), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.delete_message_pin), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - reaction.ListCustomEmojisResponse( - custom_emojis=[ - reaction.CustomEmoji(), - reaction.CustomEmoji(), - reaction.CustomEmoji(), - ], - next_page_token="abc", - ), - reaction.ListCustomEmojisResponse( - custom_emojis=[], - next_page_token="def", - ), - reaction.ListCustomEmojisResponse( - custom_emojis=[ - reaction.CustomEmoji(), - ], - next_page_token="ghi", - ), - reaction.ListCustomEmojisResponse( - custom_emojis=[ - reaction.CustomEmoji(), - reaction.CustomEmoji(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_custom_emojis( - request={}, + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_message_pin( + name="name_value", ) - assert async_pager.next_page_token == "abc" - assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) + # Establish that the 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 - assert len(responses) == 6 - assert all(isinstance(i, reaction.CustomEmoji) for i in responses) + +def test_delete_message_pin_flattened_error(): + client = ChatServiceClient( + credentials=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_message_pin( + message_pin.DeleteMessagePinRequest(), + name="name_value", + ) @pytest.mark.asyncio -async def test_list_custom_emojis_async_pages(): +async def test_delete_message_pin_flattened_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_emojis), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.delete_message_pin), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - reaction.ListCustomEmojisResponse( - custom_emojis=[ - reaction.CustomEmoji(), - reaction.CustomEmoji(), - reaction.CustomEmoji(), - ], - next_page_token="abc", - ), - reaction.ListCustomEmojisResponse( - custom_emojis=[], - next_page_token="def", - ), - reaction.ListCustomEmojisResponse( - custom_emojis=[ - reaction.CustomEmoji(), - ], - next_page_token="ghi", - ), - reaction.ListCustomEmojisResponse( - custom_emojis=[ - reaction.CustomEmoji(), - reaction.CustomEmoji(), - ], - ), - RuntimeError, + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_message_pin( + 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_message_pin_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_message_pin( + message_pin.DeleteMessagePinRequest(), + name="name_value", ) - pages = [] - async for page_ in (await client.list_custom_emojis(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", [ - reaction.DeleteCustomEmojiRequest(), + reaction.CreateCustomEmojiRequest(), {}, ], ) -def test_delete_custom_emoji(request_type, transport: str = "grpc"): +def test_create_custom_emoji(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11560,23 +11779,32 @@ def test_delete_custom_emoji(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_custom_emoji), "__call__" + type(client.transport.create_custom_emoji), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_custom_emoji(request) + call.return_value = reaction.CustomEmoji( + name="name_value", + uid="uid_value", + emoji_name="emoji_name_value", + temporary_image_uri="temporary_image_uri_value", + ) + response = client.create_custom_emoji(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = reaction.DeleteCustomEmojiRequest() + request = reaction.CreateCustomEmojiRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, reaction.CustomEmoji) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.emoji_name == "emoji_name_value" + assert response.temporary_image_uri == "temporary_image_uri_value" -def test_delete_custom_emoji_non_empty_request_with_auto_populated_field(): +def test_create_custom_emoji_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -11587,27 +11815,23 @@ def test_delete_custom_emoji_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = reaction.DeleteCustomEmojiRequest( - name="name_value", - ) + request = reaction.CreateCustomEmojiRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_custom_emoji), "__call__" + type(client.transport.create_custom_emoji), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_custom_emoji(request=request) + client.create_custom_emoji(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = reaction.DeleteCustomEmojiRequest( - name="name_value", - ) + request_msg = reaction.CreateCustomEmojiRequest() assert args[0] == request_msg -def test_delete_custom_emoji_use_cached_wrapped_rpc(): +def test_create_custom_emoji_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -11622,7 +11846,7 @@ def test_delete_custom_emoji_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_custom_emoji in client._transport._wrapped_methods + client._transport.create_custom_emoji in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -11630,16 +11854,16 @@ def test_delete_custom_emoji_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_custom_emoji] = ( + client._transport._wrapped_methods[client._transport.create_custom_emoji] = ( mock_rpc ) request = {} - client.delete_custom_emoji(request) + client.create_custom_emoji(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_custom_emoji(request) + client.create_custom_emoji(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11647,7 +11871,7 @@ def test_delete_custom_emoji_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_custom_emoji_async_use_cached_wrapped_rpc( +async def test_create_custom_emoji_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -11664,7 +11888,7 @@ async def test_delete_custom_emoji_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_custom_emoji + client._client._transport.create_custom_emoji in client._client._transport._wrapped_methods ) @@ -11672,16 +11896,16 @@ async def test_delete_custom_emoji_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_custom_emoji + client._client._transport.create_custom_emoji ] = mock_rpc request = {} - await client.delete_custom_emoji(request) + await client.create_custom_emoji(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.delete_custom_emoji(request) + await client.create_custom_emoji(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11692,11 +11916,11 @@ async def test_delete_custom_emoji_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - reaction.DeleteCustomEmojiRequest(), + reaction.CreateCustomEmojiRequest(), {}, ], ) -async def test_delete_custom_emoji_async(request_type, transport: str = "grpc_asyncio"): +async def test_create_custom_emoji_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -11708,112 +11932,60 @@ async def test_delete_custom_emoji_async(request_type, transport: str = "grpc_as # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_custom_emoji), "__call__" + type(client.transport.create_custom_emoji), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_custom_emoji(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + reaction.CustomEmoji( + name="name_value", + uid="uid_value", + emoji_name="emoji_name_value", + temporary_image_uri="temporary_image_uri_value", + ) + ) + response = await client.create_custom_emoji(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = reaction.DeleteCustomEmojiRequest() + request = reaction.CreateCustomEmojiRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_custom_emoji_field_headers(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reaction.DeleteCustomEmojiRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_custom_emoji), "__call__" - ) as call: - call.return_value = None - client.delete_custom_emoji(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_custom_emoji_field_headers_async(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = reaction.DeleteCustomEmojiRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_custom_emoji), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_custom_emoji(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + assert isinstance(response, reaction.CustomEmoji) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.emoji_name == "emoji_name_value" + assert response.temporary_image_uri == "temporary_image_uri_value" -def test_delete_custom_emoji_flattened(): +def test_create_custom_emoji_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_custom_emoji), "__call__" + type(client.transport.create_custom_emoji), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = reaction.CustomEmoji() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_custom_emoji( - name="name_value", + client.create_custom_emoji( + custom_emoji=reaction.CustomEmoji(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" + arg = args[0].custom_emoji + mock_val = reaction.CustomEmoji(name="name_value") assert arg == mock_val -def test_delete_custom_emoji_flattened_error(): +def test_create_custom_emoji_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -11821,43 +11993,45 @@ def test_delete_custom_emoji_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_custom_emoji( - reaction.DeleteCustomEmojiRequest(), - name="name_value", + client.create_custom_emoji( + reaction.CreateCustomEmojiRequest(), + custom_emoji=reaction.CustomEmoji(name="name_value"), ) @pytest.mark.asyncio -async def test_delete_custom_emoji_flattened_async(): +async def test_create_custom_emoji_flattened_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_custom_emoji), "__call__" + type(client.transport.create_custom_emoji), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = reaction.CustomEmoji() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + reaction.CustomEmoji() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_custom_emoji( - name="name_value", + response = await client.create_custom_emoji( + custom_emoji=reaction.CustomEmoji(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" + arg = args[0].custom_emoji + mock_val = reaction.CustomEmoji(name="name_value") assert arg == mock_val @pytest.mark.asyncio -async def test_delete_custom_emoji_flattened_error_async(): +async def test_create_custom_emoji_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -11865,20 +12039,20 @@ async def test_delete_custom_emoji_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_custom_emoji( - reaction.DeleteCustomEmojiRequest(), - name="name_value", + await client.create_custom_emoji( + reaction.CreateCustomEmojiRequest(), + custom_emoji=reaction.CustomEmoji(name="name_value"), ) @pytest.mark.parametrize( "request_type", [ - space_read_state.GetSpaceReadStateRequest(), + reaction.GetCustomEmojiRequest(), {}, ], ) -def test_get_space_read_state(request_type, transport: str = "grpc"): +def test_get_custom_emoji(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11889,27 +12063,31 @@ def test_get_space_read_state(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_space_read_state), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_custom_emoji), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = space_read_state.SpaceReadState( + call.return_value = reaction.CustomEmoji( name="name_value", + uid="uid_value", + emoji_name="emoji_name_value", + temporary_image_uri="temporary_image_uri_value", ) - response = client.get_space_read_state(request) + response = client.get_custom_emoji(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = space_read_state.GetSpaceReadStateRequest() + request = reaction.GetCustomEmojiRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, space_read_state.SpaceReadState) + assert isinstance(response, reaction.CustomEmoji) assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.emoji_name == "emoji_name_value" + assert response.temporary_image_uri == "temporary_image_uri_value" -def test_get_space_read_state_non_empty_request_with_auto_populated_field(): +def test_get_custom_emoji_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -11920,27 +12098,25 @@ def test_get_space_read_state_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = space_read_state.GetSpaceReadStateRequest( + request = reaction.GetCustomEmojiRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_space_read_state), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_custom_emoji), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_space_read_state(request=request) + client.get_custom_emoji(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = space_read_state.GetSpaceReadStateRequest( + request_msg = reaction.GetCustomEmojiRequest( name="name_value", ) assert args[0] == request_msg -def test_get_space_read_state_use_cached_wrapped_rpc(): +def test_get_custom_emoji_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -11954,25 +12130,23 @@ def test_get_space_read_state_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_space_read_state in client._transport._wrapped_methods - ) + assert client._transport.get_custom_emoji in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_space_read_state] = ( + client._transport._wrapped_methods[client._transport.get_custom_emoji] = ( mock_rpc ) request = {} - client.get_space_read_state(request) + client.get_custom_emoji(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_space_read_state(request) + client.get_custom_emoji(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11980,7 +12154,7 @@ def test_get_space_read_state_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_space_read_state_async_use_cached_wrapped_rpc( +async def test_get_custom_emoji_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -11997,7 +12171,7 @@ async def test_get_space_read_state_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_space_read_state + client._client._transport.get_custom_emoji in client._client._transport._wrapped_methods ) @@ -12005,16 +12179,16 @@ async def test_get_space_read_state_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_space_read_state + client._client._transport.get_custom_emoji ] = mock_rpc request = {} - await client.get_space_read_state(request) + await client.get_custom_emoji(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_space_read_state(request) + await client.get_custom_emoji(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12025,13 +12199,11 @@ async def test_get_space_read_state_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - space_read_state.GetSpaceReadStateRequest(), + reaction.GetCustomEmojiRequest(), {}, ], ) -async def test_get_space_read_state_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_get_custom_emoji_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -12042,45 +12214,47 @@ async def test_get_space_read_state_async( request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_space_read_state), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_custom_emoji), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_read_state.SpaceReadState( + reaction.CustomEmoji( name="name_value", + uid="uid_value", + emoji_name="emoji_name_value", + temporary_image_uri="temporary_image_uri_value", ) ) - response = await client.get_space_read_state(request) + response = await client.get_custom_emoji(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = space_read_state.GetSpaceReadStateRequest() + request = reaction.GetCustomEmojiRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, space_read_state.SpaceReadState) + assert isinstance(response, reaction.CustomEmoji) assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.emoji_name == "emoji_name_value" + assert response.temporary_image_uri == "temporary_image_uri_value" -def test_get_space_read_state_field_headers(): +def test_get_custom_emoji_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = space_read_state.GetSpaceReadStateRequest() + request = reaction.GetCustomEmojiRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_space_read_state), "__call__" - ) as call: - call.return_value = space_read_state.SpaceReadState() - client.get_space_read_state(request) + with mock.patch.object(type(client.transport.get_custom_emoji), "__call__") as call: + call.return_value = reaction.CustomEmoji() + client.get_custom_emoji(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -12096,25 +12270,23 @@ def test_get_space_read_state_field_headers(): @pytest.mark.asyncio -async def test_get_space_read_state_field_headers_async(): +async def test_get_custom_emoji_field_headers_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = space_read_state.GetSpaceReadStateRequest() + request = reaction.GetCustomEmojiRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_space_read_state), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_custom_emoji), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_read_state.SpaceReadState() + reaction.CustomEmoji() ) - await client.get_space_read_state(request) + await client.get_custom_emoji(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -12129,20 +12301,18 @@ async def test_get_space_read_state_field_headers_async(): ) in kw["metadata"] -def test_get_space_read_state_flattened(): +def test_get_custom_emoji_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_space_read_state), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_custom_emoji), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = space_read_state.SpaceReadState() + call.return_value = reaction.CustomEmoji() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_space_read_state( + client.get_custom_emoji( name="name_value", ) @@ -12155,7 +12325,7 @@ def test_get_space_read_state_flattened(): assert arg == mock_val -def test_get_space_read_state_flattened_error(): +def test_get_custom_emoji_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -12163,31 +12333,29 @@ def test_get_space_read_state_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_space_read_state( - space_read_state.GetSpaceReadStateRequest(), + client.get_custom_emoji( + reaction.GetCustomEmojiRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_space_read_state_flattened_async(): +async def test_get_custom_emoji_flattened_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_space_read_state), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_custom_emoji), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = space_read_state.SpaceReadState() + call.return_value = reaction.CustomEmoji() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_read_state.SpaceReadState() + reaction.CustomEmoji() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_space_read_state( + response = await client.get_custom_emoji( name="name_value", ) @@ -12201,7 +12369,7 @@ async def test_get_space_read_state_flattened_async(): @pytest.mark.asyncio -async def test_get_space_read_state_flattened_error_async(): +async def test_get_custom_emoji_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -12209,8 +12377,8 @@ async def test_get_space_read_state_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_space_read_state( - space_read_state.GetSpaceReadStateRequest(), + await client.get_custom_emoji( + reaction.GetCustomEmojiRequest(), name="name_value", ) @@ -12218,11 +12386,11 @@ async def test_get_space_read_state_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - gc_space_read_state.UpdateSpaceReadStateRequest(), + reaction.ListCustomEmojisRequest(), {}, ], ) -def test_update_space_read_state(request_type, transport: str = "grpc"): +def test_list_custom_emojis(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12234,26 +12402,26 @@ def test_update_space_read_state(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_space_read_state), "__call__" + type(client.transport.list_custom_emojis), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gc_space_read_state.SpaceReadState( - name="name_value", + call.return_value = reaction.ListCustomEmojisResponse( + next_page_token="next_page_token_value", ) - response = client.update_space_read_state(request) + response = client.list_custom_emojis(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = gc_space_read_state.UpdateSpaceReadStateRequest() + request = reaction.ListCustomEmojisRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gc_space_read_state.SpaceReadState) - assert response.name == "name_value" + assert isinstance(response, pagers.ListCustomEmojisPager) + assert response.next_page_token == "next_page_token_value" -def test_update_space_read_state_non_empty_request_with_auto_populated_field(): +def test_list_custom_emojis_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -12264,23 +12432,29 @@ def test_update_space_read_state_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = gc_space_read_state.UpdateSpaceReadStateRequest() + request = reaction.ListCustomEmojisRequest( + page_token="page_token_value", + filter="filter_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_space_read_state), "__call__" + type(client.transport.list_custom_emojis), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_space_read_state(request=request) + client.list_custom_emojis(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = gc_space_read_state.UpdateSpaceReadStateRequest() + request_msg = reaction.ListCustomEmojisRequest( + page_token="page_token_value", + filter="filter_value", + ) assert args[0] == request_msg -def test_update_space_read_state_use_cached_wrapped_rpc(): +def test_list_custom_emojis_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -12295,8 +12469,7 @@ def test_update_space_read_state_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_space_read_state - in client._transport._wrapped_methods + client._transport.list_custom_emojis in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -12304,16 +12477,16 @@ def test_update_space_read_state_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.update_space_read_state - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_custom_emojis] = ( + mock_rpc + ) request = {} - client.update_space_read_state(request) + client.list_custom_emojis(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_space_read_state(request) + client.list_custom_emojis(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12321,7 +12494,7 @@ def test_update_space_read_state_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_space_read_state_async_use_cached_wrapped_rpc( +async def test_list_custom_emojis_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -12338,7 +12511,7 @@ async def test_update_space_read_state_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_space_read_state + client._client._transport.list_custom_emojis in client._client._transport._wrapped_methods ) @@ -12346,16 +12519,16 @@ async def test_update_space_read_state_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_space_read_state + client._client._transport.list_custom_emojis ] = mock_rpc request = {} - await client.update_space_read_state(request) + await client.list_custom_emojis(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.update_space_read_state(request) + await client.list_custom_emojis(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12366,13 +12539,11 @@ async def test_update_space_read_state_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - gc_space_read_state.UpdateSpaceReadStateRequest(), + reaction.ListCustomEmojisRequest(), {}, ], ) -async def test_update_space_read_state_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_list_custom_emojis_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -12384,196 +12555,235 @@ async def test_update_space_read_state_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_space_read_state), "__call__" + type(client.transport.list_custom_emojis), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_space_read_state.SpaceReadState( - name="name_value", + reaction.ListCustomEmojisResponse( + next_page_token="next_page_token_value", ) ) - response = await client.update_space_read_state(request) + response = await client.list_custom_emojis(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = gc_space_read_state.UpdateSpaceReadStateRequest() + request = reaction.ListCustomEmojisRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gc_space_read_state.SpaceReadState) - assert response.name == "name_value" + assert isinstance(response, pagers.ListCustomEmojisAsyncPager) + assert response.next_page_token == "next_page_token_value" -def test_update_space_read_state_field_headers(): +def test_list_custom_emojis_pager(transport_name: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gc_space_read_state.UpdateSpaceReadStateRequest() - - request.space_read_state.name = "name_value" - # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_space_read_state), "__call__" + type(client.transport.list_custom_emojis), "__call__" ) as call: - call.return_value = gc_space_read_state.SpaceReadState() - client.update_space_read_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "space_read_state.name=name_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_update_space_read_state_field_headers_async(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gc_space_read_state.UpdateSpaceReadStateRequest() + # Set the response to a series of pages. + call.side_effect = ( + reaction.ListCustomEmojisResponse( + custom_emojis=[ + reaction.CustomEmoji(), + reaction.CustomEmoji(), + reaction.CustomEmoji(), + ], + next_page_token="abc", + ), + reaction.ListCustomEmojisResponse( + custom_emojis=[], + next_page_token="def", + ), + reaction.ListCustomEmojisResponse( + custom_emojis=[ + reaction.CustomEmoji(), + ], + next_page_token="ghi", + ), + reaction.ListCustomEmojisResponse( + custom_emojis=[ + reaction.CustomEmoji(), + reaction.CustomEmoji(), + ], + ), + RuntimeError, + ) - request.space_read_state.name = "name_value" + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.list_custom_emojis(request={}, retry=retry, timeout=timeout) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_space_read_state), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_space_read_state.SpaceReadState() - ) - await client.update_space_read_state(request) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "space_read_state.name=name_value", - ) in kw["metadata"] + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, reaction.CustomEmoji) for i in results) -def test_update_space_read_state_flattened(): +def test_list_custom_emojis_pages(transport_name: str = "grpc"): client = ChatServiceClient( 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.update_space_read_state), "__call__" + type(client.transport.list_custom_emojis), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = gc_space_read_state.SpaceReadState() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_space_read_state( - space_read_state=gc_space_read_state.SpaceReadState(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].space_read_state - mock_val = gc_space_read_state.SpaceReadState(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_space_read_state_flattened_error(): - client = ChatServiceClient( - credentials=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_space_read_state( - gc_space_read_state.UpdateSpaceReadStateRequest(), - space_read_state=gc_space_read_state.SpaceReadState(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + # Set the response to a series of pages. + call.side_effect = ( + reaction.ListCustomEmojisResponse( + custom_emojis=[ + reaction.CustomEmoji(), + reaction.CustomEmoji(), + reaction.CustomEmoji(), + ], + next_page_token="abc", + ), + reaction.ListCustomEmojisResponse( + custom_emojis=[], + next_page_token="def", + ), + reaction.ListCustomEmojisResponse( + custom_emojis=[ + reaction.CustomEmoji(), + ], + next_page_token="ghi", + ), + reaction.ListCustomEmojisResponse( + custom_emojis=[ + reaction.CustomEmoji(), + reaction.CustomEmoji(), + ], + ), + RuntimeError, ) + pages = list(client.list_custom_emojis(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_update_space_read_state_flattened_async(): +async def test_list_custom_emojis_async_pager(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_space_read_state), "__call__" + type(client.transport.list_custom_emojis), + "__call__", + new_callable=mock.AsyncMock, ) as call: - # Designate an appropriate return value for the call. - call.return_value = gc_space_read_state.SpaceReadState() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_space_read_state.SpaceReadState() + # Set the response to a series of pages. + call.side_effect = ( + reaction.ListCustomEmojisResponse( + custom_emojis=[ + reaction.CustomEmoji(), + reaction.CustomEmoji(), + reaction.CustomEmoji(), + ], + next_page_token="abc", + ), + reaction.ListCustomEmojisResponse( + custom_emojis=[], + next_page_token="def", + ), + reaction.ListCustomEmojisResponse( + custom_emojis=[ + reaction.CustomEmoji(), + ], + next_page_token="ghi", + ), + reaction.ListCustomEmojisResponse( + custom_emojis=[ + reaction.CustomEmoji(), + reaction.CustomEmoji(), + ], + ), + RuntimeError, ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_space_read_state( - space_read_state=gc_space_read_state.SpaceReadState(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + async_pager = await client.list_custom_emojis( + request={}, ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].space_read_state - mock_val = gc_space_read_state.SpaceReadState(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 + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, reaction.CustomEmoji) for i in responses) @pytest.mark.asyncio -async def test_update_space_read_state_flattened_error_async(): +async def test_list_custom_emojis_async_pages(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_space_read_state( - gc_space_read_state.UpdateSpaceReadStateRequest(), - space_read_state=gc_space_read_state.SpaceReadState(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_emojis), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + reaction.ListCustomEmojisResponse( + custom_emojis=[ + reaction.CustomEmoji(), + reaction.CustomEmoji(), + reaction.CustomEmoji(), + ], + next_page_token="abc", + ), + reaction.ListCustomEmojisResponse( + custom_emojis=[], + next_page_token="def", + ), + reaction.ListCustomEmojisResponse( + custom_emojis=[ + reaction.CustomEmoji(), + ], + next_page_token="ghi", + ), + reaction.ListCustomEmojisResponse( + custom_emojis=[ + reaction.CustomEmoji(), + reaction.CustomEmoji(), + ], + ), + RuntimeError, ) + pages = [] + async for page_ in (await client.list_custom_emojis(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", [ - thread_read_state.GetThreadReadStateRequest(), + reaction.DeleteCustomEmojiRequest(), {}, ], ) -def test_get_thread_read_state(request_type, transport: str = "grpc"): +def test_delete_custom_emoji(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12585,26 +12795,23 @@ def test_get_thread_read_state(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_thread_read_state), "__call__" + type(client.transport.delete_custom_emoji), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = thread_read_state.ThreadReadState( - name="name_value", - ) - response = client.get_thread_read_state(request) + call.return_value = None + response = client.delete_custom_emoji(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = thread_read_state.GetThreadReadStateRequest() + request = reaction.DeleteCustomEmojiRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, thread_read_state.ThreadReadState) - assert response.name == "name_value" + assert response is None -def test_get_thread_read_state_non_empty_request_with_auto_populated_field(): +def test_delete_custom_emoji_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -12615,27 +12822,27 @@ def test_get_thread_read_state_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = thread_read_state.GetThreadReadStateRequest( + request = reaction.DeleteCustomEmojiRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_thread_read_state), "__call__" + type(client.transport.delete_custom_emoji), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_thread_read_state(request=request) + client.delete_custom_emoji(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = thread_read_state.GetThreadReadStateRequest( + request_msg = reaction.DeleteCustomEmojiRequest( name="name_value", ) assert args[0] == request_msg -def test_get_thread_read_state_use_cached_wrapped_rpc(): +def test_delete_custom_emoji_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -12650,8 +12857,7 @@ def test_get_thread_read_state_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_thread_read_state - in client._transport._wrapped_methods + client._transport.delete_custom_emoji in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -12659,16 +12865,16 @@ def test_get_thread_read_state_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_thread_read_state] = ( + client._transport._wrapped_methods[client._transport.delete_custom_emoji] = ( mock_rpc ) request = {} - client.get_thread_read_state(request) + client.delete_custom_emoji(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_thread_read_state(request) + client.delete_custom_emoji(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12676,7 +12882,7 @@ def test_get_thread_read_state_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_thread_read_state_async_use_cached_wrapped_rpc( +async def test_delete_custom_emoji_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -12693,7 +12899,7 @@ async def test_get_thread_read_state_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_thread_read_state + client._client._transport.delete_custom_emoji in client._client._transport._wrapped_methods ) @@ -12701,16 +12907,16 @@ async def test_get_thread_read_state_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_thread_read_state + client._client._transport.delete_custom_emoji ] = mock_rpc request = {} - await client.get_thread_read_state(request) + await client.delete_custom_emoji(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_thread_read_state(request) + await client.delete_custom_emoji(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12721,13 +12927,11 @@ async def test_get_thread_read_state_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - thread_read_state.GetThreadReadStateRequest(), + reaction.DeleteCustomEmojiRequest(), {}, ], ) -async def test_get_thread_read_state_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_delete_custom_emoji_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -12739,44 +12943,39 @@ async def test_get_thread_read_state_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_thread_read_state), "__call__" + type(client.transport.delete_custom_emoji), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - thread_read_state.ThreadReadState( - name="name_value", - ) - ) - response = await client.get_thread_read_state(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_custom_emoji(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = thread_read_state.GetThreadReadStateRequest() + request = reaction.DeleteCustomEmojiRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, thread_read_state.ThreadReadState) - assert response.name == "name_value" + assert response is None -def test_get_thread_read_state_field_headers(): +def test_delete_custom_emoji_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = thread_read_state.GetThreadReadStateRequest() + request = reaction.DeleteCustomEmojiRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_thread_read_state), "__call__" + type(client.transport.delete_custom_emoji), "__call__" ) as call: - call.return_value = thread_read_state.ThreadReadState() - client.get_thread_read_state(request) + call.return_value = None + client.delete_custom_emoji(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -12792,25 +12991,23 @@ def test_get_thread_read_state_field_headers(): @pytest.mark.asyncio -async def test_get_thread_read_state_field_headers_async(): +async def test_delete_custom_emoji_field_headers_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = thread_read_state.GetThreadReadStateRequest() + request = reaction.DeleteCustomEmojiRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_thread_read_state), "__call__" + type(client.transport.delete_custom_emoji), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - thread_read_state.ThreadReadState() - ) - await client.get_thread_read_state(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_custom_emoji(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -12825,20 +13022,20 @@ async def test_get_thread_read_state_field_headers_async(): ) in kw["metadata"] -def test_get_thread_read_state_flattened(): +def test_delete_custom_emoji_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_thread_read_state), "__call__" + type(client.transport.delete_custom_emoji), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = thread_read_state.ThreadReadState() + call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_thread_read_state( + client.delete_custom_emoji( name="name_value", ) @@ -12851,7 +13048,7 @@ def test_get_thread_read_state_flattened(): assert arg == mock_val -def test_get_thread_read_state_flattened_error(): +def test_delete_custom_emoji_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -12859,31 +13056,29 @@ def test_get_thread_read_state_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_thread_read_state( - thread_read_state.GetThreadReadStateRequest(), + client.delete_custom_emoji( + reaction.DeleteCustomEmojiRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_thread_read_state_flattened_async(): +async def test_delete_custom_emoji_flattened_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_thread_read_state), "__call__" + type(client.transport.delete_custom_emoji), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = thread_read_state.ThreadReadState() + call.return_value = None - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - thread_read_state.ThreadReadState() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_thread_read_state( + response = await client.delete_custom_emoji( name="name_value", ) @@ -12897,7 +13092,7 @@ async def test_get_thread_read_state_flattened_async(): @pytest.mark.asyncio -async def test_get_thread_read_state_flattened_error_async(): +async def test_delete_custom_emoji_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -12905,8 +13100,8 @@ async def test_get_thread_read_state_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_thread_read_state( - thread_read_state.GetThreadReadStateRequest(), + await client.delete_custom_emoji( + reaction.DeleteCustomEmojiRequest(), name="name_value", ) @@ -12914,11 +13109,11 @@ async def test_get_thread_read_state_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - availability.GetAvailabilityRequest(), + space_read_state.GetSpaceReadStateRequest(), {}, ], ) -def test_get_availability(request_type, transport: str = "grpc"): +def test_get_space_read_state(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12929,27 +13124,27 @@ def test_get_availability(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_availability), "__call__") as call: + with mock.patch.object( + type(client.transport.get_space_read_state), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = availability.Availability( + call.return_value = space_read_state.SpaceReadState( name="name_value", - state=availability.Availability.State.ACTIVE, ) - response = client.get_availability(request) + response = client.get_space_read_state(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = availability.GetAvailabilityRequest() + request = space_read_state.GetSpaceReadStateRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, availability.Availability) + assert isinstance(response, space_read_state.SpaceReadState) assert response.name == "name_value" - assert response.state == availability.Availability.State.ACTIVE -def test_get_availability_non_empty_request_with_auto_populated_field(): +def test_get_space_read_state_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -12960,25 +13155,27 @@ def test_get_availability_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = availability.GetAvailabilityRequest( + request = space_read_state.GetSpaceReadStateRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_availability), "__call__") as call: + with mock.patch.object( + type(client.transport.get_space_read_state), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_availability(request=request) + client.get_space_read_state(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = availability.GetAvailabilityRequest( + request_msg = space_read_state.GetSpaceReadStateRequest( name="name_value", ) assert args[0] == request_msg -def test_get_availability_use_cached_wrapped_rpc(): +def test_get_space_read_state_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -12992,23 +13189,25 @@ def test_get_availability_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_availability in client._transport._wrapped_methods + assert ( + client._transport.get_space_read_state in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_availability] = ( + client._transport._wrapped_methods[client._transport.get_space_read_state] = ( mock_rpc ) request = {} - client.get_availability(request) + client.get_space_read_state(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_availability(request) + client.get_space_read_state(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13016,7 +13215,7 @@ def test_get_availability_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_availability_async_use_cached_wrapped_rpc( +async def test_get_space_read_state_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -13033,7 +13232,7 @@ async def test_get_availability_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_availability + client._client._transport.get_space_read_state in client._client._transport._wrapped_methods ) @@ -13041,16 +13240,16 @@ async def test_get_availability_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_availability + client._client._transport.get_space_read_state ] = mock_rpc request = {} - await client.get_availability(request) + await client.get_space_read_state(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_availability(request) + await client.get_space_read_state(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13061,11 +13260,13 @@ async def test_get_availability_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - availability.GetAvailabilityRequest(), + space_read_state.GetSpaceReadStateRequest(), {}, ], ) -async def test_get_availability_async(request_type, transport: str = "grpc_asyncio"): +async def test_get_space_read_state_async( + request_type, transport: str = "grpc_asyncio" +): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -13076,43 +13277,45 @@ async def test_get_availability_async(request_type, transport: str = "grpc_async request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_availability), "__call__") as call: + with mock.patch.object( + type(client.transport.get_space_read_state), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - availability.Availability( + space_read_state.SpaceReadState( name="name_value", - state=availability.Availability.State.ACTIVE, ) ) - response = await client.get_availability(request) + response = await client.get_space_read_state(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = availability.GetAvailabilityRequest() + request = space_read_state.GetSpaceReadStateRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, availability.Availability) + assert isinstance(response, space_read_state.SpaceReadState) assert response.name == "name_value" - assert response.state == availability.Availability.State.ACTIVE -def test_get_availability_field_headers(): +def test_get_space_read_state_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = availability.GetAvailabilityRequest() + request = space_read_state.GetSpaceReadStateRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_availability), "__call__") as call: - call.return_value = availability.Availability() - client.get_availability(request) + with mock.patch.object( + type(client.transport.get_space_read_state), "__call__" + ) as call: + call.return_value = space_read_state.SpaceReadState() + client.get_space_read_state(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -13128,23 +13331,25 @@ def test_get_availability_field_headers(): @pytest.mark.asyncio -async def test_get_availability_field_headers_async(): +async def test_get_space_read_state_field_headers_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = availability.GetAvailabilityRequest() + request = space_read_state.GetSpaceReadStateRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_availability), "__call__") as call: + with mock.patch.object( + type(client.transport.get_space_read_state), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - availability.Availability() + space_read_state.SpaceReadState() ) - await client.get_availability(request) + await client.get_space_read_state(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -13159,18 +13364,20 @@ async def test_get_availability_field_headers_async(): ) in kw["metadata"] -def test_get_availability_flattened(): +def test_get_space_read_state_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_availability), "__call__") as call: + with mock.patch.object( + type(client.transport.get_space_read_state), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = availability.Availability() + call.return_value = space_read_state.SpaceReadState() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_availability( + client.get_space_read_state( name="name_value", ) @@ -13183,7 +13390,7 @@ def test_get_availability_flattened(): assert arg == mock_val -def test_get_availability_flattened_error(): +def test_get_space_read_state_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -13191,29 +13398,31 @@ def test_get_availability_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_availability( - availability.GetAvailabilityRequest(), + client.get_space_read_state( + space_read_state.GetSpaceReadStateRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_availability_flattened_async(): +async def test_get_space_read_state_flattened_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_availability), "__call__") as call: + with mock.patch.object( + type(client.transport.get_space_read_state), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = availability.Availability() + call.return_value = space_read_state.SpaceReadState() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - availability.Availability() + space_read_state.SpaceReadState() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_availability( + response = await client.get_space_read_state( name="name_value", ) @@ -13227,7 +13436,7 @@ async def test_get_availability_flattened_async(): @pytest.mark.asyncio -async def test_get_availability_flattened_error_async(): +async def test_get_space_read_state_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -13235,8 +13444,8 @@ async def test_get_availability_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_availability( - availability.GetAvailabilityRequest(), + await client.get_space_read_state( + space_read_state.GetSpaceReadStateRequest(), name="name_value", ) @@ -13244,11 +13453,11 @@ async def test_get_availability_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - availability.MarkAsActiveRequest(), + gc_space_read_state.UpdateSpaceReadStateRequest(), {}, ], ) -def test_mark_as_active(request_type, transport: str = "grpc"): +def test_update_space_read_state(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13259,27 +13468,27 @@ def test_mark_as_active(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mark_as_active), "__call__") as call: + with mock.patch.object( + type(client.transport.update_space_read_state), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = availability.Availability( + call.return_value = gc_space_read_state.SpaceReadState( name="name_value", - state=availability.Availability.State.ACTIVE, ) - response = client.mark_as_active(request) + response = client.update_space_read_state(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = availability.MarkAsActiveRequest() + request = gc_space_read_state.UpdateSpaceReadStateRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, availability.Availability) + assert isinstance(response, gc_space_read_state.SpaceReadState) assert response.name == "name_value" - assert response.state == availability.Availability.State.ACTIVE -def test_mark_as_active_non_empty_request_with_auto_populated_field(): +def test_update_space_read_state_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -13290,25 +13499,23 @@ def test_mark_as_active_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = availability.MarkAsActiveRequest( - name="name_value", - ) + request = gc_space_read_state.UpdateSpaceReadStateRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mark_as_active), "__call__") as call: + with mock.patch.object( + type(client.transport.update_space_read_state), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.mark_as_active(request=request) + client.update_space_read_state(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = availability.MarkAsActiveRequest( - name="name_value", - ) + request_msg = gc_space_read_state.UpdateSpaceReadStateRequest() assert args[0] == request_msg -def test_mark_as_active_use_cached_wrapped_rpc(): +def test_update_space_read_state_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -13322,21 +13529,26 @@ def test_mark_as_active_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.mark_as_active in client._transport._wrapped_methods + assert ( + client._transport.update_space_read_state + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.mark_as_active] = mock_rpc + client._transport._wrapped_methods[ + client._transport.update_space_read_state + ] = mock_rpc request = {} - client.mark_as_active(request) + client.update_space_read_state(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.mark_as_active(request) + client.update_space_read_state(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13344,7 +13556,7 @@ def test_mark_as_active_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_mark_as_active_async_use_cached_wrapped_rpc( +async def test_update_space_read_state_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -13361,7 +13573,7 @@ async def test_mark_as_active_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.mark_as_active + client._client._transport.update_space_read_state in client._client._transport._wrapped_methods ) @@ -13369,16 +13581,16 @@ async def test_mark_as_active_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.mark_as_active + client._client._transport.update_space_read_state ] = mock_rpc request = {} - await client.mark_as_active(request) + await client.update_space_read_state(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.mark_as_active(request) + await client.update_space_read_state(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13389,11 +13601,13 @@ async def test_mark_as_active_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - availability.MarkAsActiveRequest(), + gc_space_read_state.UpdateSpaceReadStateRequest(), {}, ], ) -async def test_mark_as_active_async(request_type, transport: str = "grpc_asyncio"): +async def test_update_space_read_state_async( + request_type, transport: str = "grpc_asyncio" +): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -13404,43 +13618,45 @@ async def test_mark_as_active_async(request_type, transport: str = "grpc_asyncio request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mark_as_active), "__call__") as call: + with mock.patch.object( + type(client.transport.update_space_read_state), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - availability.Availability( + gc_space_read_state.SpaceReadState( name="name_value", - state=availability.Availability.State.ACTIVE, ) ) - response = await client.mark_as_active(request) + response = await client.update_space_read_state(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = availability.MarkAsActiveRequest() + request = gc_space_read_state.UpdateSpaceReadStateRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, availability.Availability) + assert isinstance(response, gc_space_read_state.SpaceReadState) assert response.name == "name_value" - assert response.state == availability.Availability.State.ACTIVE -def test_mark_as_active_field_headers(): +def test_update_space_read_state_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = availability.MarkAsActiveRequest() + request = gc_space_read_state.UpdateSpaceReadStateRequest() - request.name = "name_value" + request.space_read_state.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mark_as_active), "__call__") as call: - call.return_value = availability.Availability() - client.mark_as_active(request) + with mock.patch.object( + type(client.transport.update_space_read_state), "__call__" + ) as call: + call.return_value = gc_space_read_state.SpaceReadState() + client.update_space_read_state(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -13451,28 +13667,30 @@ def test_mark_as_active_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "space_read_state.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_mark_as_active_field_headers_async(): +async def test_update_space_read_state_field_headers_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = availability.MarkAsActiveRequest() + request = gc_space_read_state.UpdateSpaceReadStateRequest() - request.name = "name_value" + request.space_read_state.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mark_as_active), "__call__") as call: + with mock.patch.object( + type(client.transport.update_space_read_state), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - availability.Availability() + gc_space_read_state.SpaceReadState() ) - await client.mark_as_active(request) + await client.update_space_read_state(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -13483,18 +13701,114 @@ async def test_mark_as_active_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "space_read_state.name=name_value", ) in kw["metadata"] +def test_update_space_read_state_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_space_read_state), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gc_space_read_state.SpaceReadState() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_space_read_state( + space_read_state=gc_space_read_state.SpaceReadState(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].space_read_state + mock_val = gc_space_read_state.SpaceReadState(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_space_read_state_flattened_error(): + client = ChatServiceClient( + credentials=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_space_read_state( + gc_space_read_state.UpdateSpaceReadStateRequest(), + space_read_state=gc_space_read_state.SpaceReadState(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_space_read_state_flattened_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_space_read_state), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gc_space_read_state.SpaceReadState() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_space_read_state.SpaceReadState() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_space_read_state( + space_read_state=gc_space_read_state.SpaceReadState(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].space_read_state + mock_val = gc_space_read_state.SpaceReadState(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_space_read_state_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_space_read_state( + gc_space_read_state.UpdateSpaceReadStateRequest(), + space_read_state=gc_space_read_state.SpaceReadState(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + @pytest.mark.parametrize( "request_type", [ - availability.MarkAsAwayRequest(), + thread_read_state.GetThreadReadStateRequest(), {}, ], ) -def test_mark_as_away(request_type, transport: str = "grpc"): +def test_get_thread_read_state(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13505,27 +13819,27 @@ def test_mark_as_away(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mark_as_away), "__call__") as call: + with mock.patch.object( + type(client.transport.get_thread_read_state), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = availability.Availability( + call.return_value = thread_read_state.ThreadReadState( name="name_value", - state=availability.Availability.State.ACTIVE, ) - response = client.mark_as_away(request) + response = client.get_thread_read_state(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = availability.MarkAsAwayRequest() + request = thread_read_state.GetThreadReadStateRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, availability.Availability) + assert isinstance(response, thread_read_state.ThreadReadState) assert response.name == "name_value" - assert response.state == availability.Availability.State.ACTIVE -def test_mark_as_away_non_empty_request_with_auto_populated_field(): +def test_get_thread_read_state_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -13536,25 +13850,27 @@ def test_mark_as_away_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = availability.MarkAsAwayRequest( + request = thread_read_state.GetThreadReadStateRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mark_as_away), "__call__") as call: + with mock.patch.object( + type(client.transport.get_thread_read_state), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.mark_as_away(request=request) + client.get_thread_read_state(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = availability.MarkAsAwayRequest( + request_msg = thread_read_state.GetThreadReadStateRequest( name="name_value", ) assert args[0] == request_msg -def test_mark_as_away_use_cached_wrapped_rpc(): +def test_get_thread_read_state_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -13568,21 +13884,26 @@ def test_mark_as_away_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.mark_as_away in client._transport._wrapped_methods + assert ( + client._transport.get_thread_read_state + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.mark_as_away] = mock_rpc + client._transport._wrapped_methods[client._transport.get_thread_read_state] = ( + mock_rpc + ) request = {} - client.mark_as_away(request) + client.get_thread_read_state(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.mark_as_away(request) + client.get_thread_read_state(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13590,7 +13911,7 @@ def test_mark_as_away_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_mark_as_away_async_use_cached_wrapped_rpc( +async def test_get_thread_read_state_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -13607,7 +13928,7 @@ async def test_mark_as_away_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.mark_as_away + client._client._transport.get_thread_read_state in client._client._transport._wrapped_methods ) @@ -13615,16 +13936,16 @@ async def test_mark_as_away_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.mark_as_away + client._client._transport.get_thread_read_state ] = mock_rpc request = {} - await client.mark_as_away(request) + await client.get_thread_read_state(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.mark_as_away(request) + await client.get_thread_read_state(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13635,11 +13956,13 @@ async def test_mark_as_away_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - availability.MarkAsAwayRequest(), + thread_read_state.GetThreadReadStateRequest(), {}, ], ) -async def test_mark_as_away_async(request_type, transport: str = "grpc_asyncio"): +async def test_get_thread_read_state_async( + request_type, transport: str = "grpc_asyncio" +): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -13650,43 +13973,45 @@ async def test_mark_as_away_async(request_type, transport: str = "grpc_asyncio") request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mark_as_away), "__call__") as call: + with mock.patch.object( + type(client.transport.get_thread_read_state), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - availability.Availability( + thread_read_state.ThreadReadState( name="name_value", - state=availability.Availability.State.ACTIVE, ) ) - response = await client.mark_as_away(request) + response = await client.get_thread_read_state(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = availability.MarkAsAwayRequest() + request = thread_read_state.GetThreadReadStateRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, availability.Availability) + assert isinstance(response, thread_read_state.ThreadReadState) assert response.name == "name_value" - assert response.state == availability.Availability.State.ACTIVE -def test_mark_as_away_field_headers(): +def test_get_thread_read_state_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = availability.MarkAsAwayRequest() + request = thread_read_state.GetThreadReadStateRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mark_as_away), "__call__") as call: - call.return_value = availability.Availability() - client.mark_as_away(request) + with mock.patch.object( + type(client.transport.get_thread_read_state), "__call__" + ) as call: + call.return_value = thread_read_state.ThreadReadState() + client.get_thread_read_state(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -13702,23 +14027,25 @@ def test_mark_as_away_field_headers(): @pytest.mark.asyncio -async def test_mark_as_away_field_headers_async(): +async def test_get_thread_read_state_field_headers_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = availability.MarkAsAwayRequest() + request = thread_read_state.GetThreadReadStateRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mark_as_away), "__call__") as call: + with mock.patch.object( + type(client.transport.get_thread_read_state), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - availability.Availability() + thread_read_state.ThreadReadState() ) - await client.mark_as_away(request) + await client.get_thread_read_state(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -13733,14 +14060,100 @@ async def test_mark_as_away_field_headers_async(): ) in kw["metadata"] +def test_get_thread_read_state_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_thread_read_state), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = thread_read_state.ThreadReadState() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_thread_read_state( + 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_thread_read_state_flattened_error(): + client = ChatServiceClient( + credentials=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_thread_read_state( + thread_read_state.GetThreadReadStateRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_thread_read_state_flattened_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_thread_read_state), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = thread_read_state.ThreadReadState() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + thread_read_state.ThreadReadState() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_thread_read_state( + 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_thread_read_state_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_thread_read_state( + thread_read_state.GetThreadReadStateRequest(), + name="name_value", + ) + + @pytest.mark.parametrize( "request_type", [ - availability.MarkAsDoNotDisturbRequest(), + availability.GetAvailabilityRequest(), {}, ], ) -def test_mark_as_do_not_disturb(request_type, transport: str = "grpc"): +def test_get_availability(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13751,20 +14164,18 @@ def test_mark_as_do_not_disturb(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_as_do_not_disturb), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_availability), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = availability.Availability( name="name_value", state=availability.Availability.State.ACTIVE, ) - response = client.mark_as_do_not_disturb(request) + response = client.get_availability(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = availability.MarkAsDoNotDisturbRequest() + request = availability.GetAvailabilityRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -13773,7 +14184,7 @@ def test_mark_as_do_not_disturb(request_type, transport: str = "grpc"): assert response.state == availability.Availability.State.ACTIVE -def test_mark_as_do_not_disturb_non_empty_request_with_auto_populated_field(): +def test_get_availability_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -13784,27 +14195,25 @@ def test_mark_as_do_not_disturb_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = availability.MarkAsDoNotDisturbRequest( + request = availability.GetAvailabilityRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_as_do_not_disturb), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_availability), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.mark_as_do_not_disturb(request=request) + client.get_availability(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = availability.MarkAsDoNotDisturbRequest( + request_msg = availability.GetAvailabilityRequest( name="name_value", ) assert args[0] == request_msg -def test_mark_as_do_not_disturb_use_cached_wrapped_rpc(): +def test_get_availability_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -13818,26 +14227,23 @@ def test_mark_as_do_not_disturb_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.mark_as_do_not_disturb - in client._transport._wrapped_methods - ) + assert client._transport.get_availability in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.mark_as_do_not_disturb] = ( + client._transport._wrapped_methods[client._transport.get_availability] = ( mock_rpc ) request = {} - client.mark_as_do_not_disturb(request) + client.get_availability(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.mark_as_do_not_disturb(request) + client.get_availability(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13845,7 +14251,7 @@ def test_mark_as_do_not_disturb_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_mark_as_do_not_disturb_async_use_cached_wrapped_rpc( +async def test_get_availability_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -13862,7 +14268,7 @@ async def test_mark_as_do_not_disturb_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.mark_as_do_not_disturb + client._client._transport.get_availability in client._client._transport._wrapped_methods ) @@ -13870,16 +14276,16 @@ async def test_mark_as_do_not_disturb_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.mark_as_do_not_disturb + client._client._transport.get_availability ] = mock_rpc request = {} - await client.mark_as_do_not_disturb(request) + await client.get_availability(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.mark_as_do_not_disturb(request) + await client.get_availability(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13890,13 +14296,11 @@ async def test_mark_as_do_not_disturb_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - availability.MarkAsDoNotDisturbRequest(), + availability.GetAvailabilityRequest(), {}, ], ) -async def test_mark_as_do_not_disturb_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_get_availability_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -13907,9 +14311,7 @@ async def test_mark_as_do_not_disturb_async( request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_as_do_not_disturb), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_availability), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( availability.Availability( @@ -13917,12 +14319,12 @@ async def test_mark_as_do_not_disturb_async( state=availability.Availability.State.ACTIVE, ) ) - response = await client.mark_as_do_not_disturb(request) + response = await client.get_availability(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = availability.MarkAsDoNotDisturbRequest() + request = availability.GetAvailabilityRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -13931,23 +14333,21 @@ async def test_mark_as_do_not_disturb_async( assert response.state == availability.Availability.State.ACTIVE -def test_mark_as_do_not_disturb_field_headers(): +def test_get_availability_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = availability.MarkAsDoNotDisturbRequest() + request = availability.GetAvailabilityRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_as_do_not_disturb), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_availability), "__call__") as call: call.return_value = availability.Availability() - client.mark_as_do_not_disturb(request) + client.get_availability(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -13963,25 +14363,23 @@ def test_mark_as_do_not_disturb_field_headers(): @pytest.mark.asyncio -async def test_mark_as_do_not_disturb_field_headers_async(): +async def test_get_availability_field_headers_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = availability.MarkAsDoNotDisturbRequest() + request = availability.GetAvailabilityRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_as_do_not_disturb), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_availability), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( availability.Availability() ) - await client.mark_as_do_not_disturb(request) + await client.get_availability(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -13996,14 +14394,96 @@ async def test_mark_as_do_not_disturb_field_headers_async(): ) in kw["metadata"] +def test_get_availability_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_availability), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = availability.Availability() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_availability( + 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_availability_flattened_error(): + client = ChatServiceClient( + credentials=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_availability( + availability.GetAvailabilityRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_availability_flattened_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_availability), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = availability.Availability() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + availability.Availability() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_availability( + 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_availability_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_availability( + availability.GetAvailabilityRequest(), + name="name_value", + ) + + @pytest.mark.parametrize( "request_type", [ - gc_availability.UpdateAvailabilityRequest(), + availability.MarkAsActiveRequest(), {}, ], ) -def test_update_availability(request_type, transport: str = "grpc"): +def test_mark_as_active(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14014,29 +14494,27 @@ def test_update_availability(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_availability), "__call__" - ) as call: + with mock.patch.object(type(client.transport.mark_as_active), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = gc_availability.Availability( + call.return_value = availability.Availability( name="name_value", - state=gc_availability.Availability.State.ACTIVE, + state=availability.Availability.State.ACTIVE, ) - response = client.update_availability(request) + response = client.mark_as_active(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = gc_availability.UpdateAvailabilityRequest() + request = availability.MarkAsActiveRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gc_availability.Availability) + assert isinstance(response, availability.Availability) assert response.name == "name_value" - assert response.state == gc_availability.Availability.State.ACTIVE + assert response.state == availability.Availability.State.ACTIVE -def test_update_availability_non_empty_request_with_auto_populated_field(): +def test_mark_as_active_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -14047,23 +14525,25 @@ def test_update_availability_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = gc_availability.UpdateAvailabilityRequest() + request = availability.MarkAsActiveRequest( + name="name_value", + ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_availability), "__call__" - ) as call: + with mock.patch.object(type(client.transport.mark_as_active), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_availability(request=request) + client.mark_as_active(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = gc_availability.UpdateAvailabilityRequest() + request_msg = availability.MarkAsActiveRequest( + name="name_value", + ) assert args[0] == request_msg -def test_update_availability_use_cached_wrapped_rpc(): +def test_mark_as_active_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -14077,25 +14557,21 @@ def test_update_availability_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_availability in client._transport._wrapped_methods - ) + assert client._transport.mark_as_active in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_availability] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.mark_as_active] = mock_rpc request = {} - client.update_availability(request) + client.mark_as_active(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_availability(request) + client.mark_as_active(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -14103,7 +14579,7 @@ def test_update_availability_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_availability_async_use_cached_wrapped_rpc( +async def test_mark_as_active_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -14120,7 +14596,7 @@ async def test_update_availability_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_availability + client._client._transport.mark_as_active in client._client._transport._wrapped_methods ) @@ -14128,16 +14604,16 @@ async def test_update_availability_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_availability + client._client._transport.mark_as_active ] = mock_rpc request = {} - await client.update_availability(request) + await client.mark_as_active(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.update_availability(request) + await client.mark_as_active(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -14148,11 +14624,11 @@ async def test_update_availability_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - gc_availability.UpdateAvailabilityRequest(), + availability.MarkAsActiveRequest(), {}, ], ) -async def test_update_availability_async(request_type, transport: str = "grpc_asyncio"): +async def test_mark_as_active_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -14163,47 +14639,43 @@ async def test_update_availability_async(request_type, transport: str = "grpc_as request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_availability), "__call__" - ) as call: + with mock.patch.object(type(client.transport.mark_as_active), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_availability.Availability( + availability.Availability( name="name_value", - state=gc_availability.Availability.State.ACTIVE, + state=availability.Availability.State.ACTIVE, ) ) - response = await client.update_availability(request) + response = await client.mark_as_active(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = gc_availability.UpdateAvailabilityRequest() + request = availability.MarkAsActiveRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gc_availability.Availability) + assert isinstance(response, availability.Availability) assert response.name == "name_value" - assert response.state == gc_availability.Availability.State.ACTIVE + assert response.state == availability.Availability.State.ACTIVE -def test_update_availability_field_headers(): +def test_mark_as_active_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = gc_availability.UpdateAvailabilityRequest() + request = availability.MarkAsActiveRequest() - request.availability.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_availability), "__call__" - ) as call: - call.return_value = gc_availability.Availability() - client.update_availability(request) + with mock.patch.object(type(client.transport.mark_as_active), "__call__") as call: + call.return_value = availability.Availability() + client.mark_as_active(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -14214,30 +14686,28 @@ def test_update_availability_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "availability.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_availability_field_headers_async(): +async def test_mark_as_active_field_headers_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = gc_availability.UpdateAvailabilityRequest() + request = availability.MarkAsActiveRequest() - request.availability.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_availability), "__call__" - ) as call: + with mock.patch.object(type(client.transport.mark_as_active), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_availability.Availability() + availability.Availability() ) - await client.update_availability(request) + await client.mark_as_active(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -14248,114 +14718,18 @@ async def test_update_availability_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "availability.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_availability_flattened(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_availability), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = gc_availability.Availability() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_availability( - availability=gc_availability.Availability(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].availability - mock_val = gc_availability.Availability(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_availability_flattened_error(): - client = ChatServiceClient( - credentials=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_availability( - gc_availability.UpdateAvailabilityRequest(), - availability=gc_availability.Availability(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -@pytest.mark.asyncio -async def test_update_availability_flattened_async(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_availability), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = gc_availability.Availability() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_availability.Availability() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_availability( - availability=gc_availability.Availability(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].availability - mock_val = gc_availability.Availability(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_availability_flattened_error_async(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_availability( - gc_availability.UpdateAvailabilityRequest(), - availability=gc_availability.Availability(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - @pytest.mark.parametrize( "request_type", [ - space_event.GetSpaceEventRequest(), + availability.MarkAsAwayRequest(), {}, ], ) -def test_get_space_event(request_type, transport: str = "grpc"): +def test_mark_as_away(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14366,27 +14740,27 @@ def test_get_space_event(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: + with mock.patch.object(type(client.transport.mark_as_away), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = space_event.SpaceEvent( + call.return_value = availability.Availability( name="name_value", - event_type="event_type_value", + state=availability.Availability.State.ACTIVE, ) - response = client.get_space_event(request) + response = client.mark_as_away(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = space_event.GetSpaceEventRequest() + request = availability.MarkAsAwayRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, space_event.SpaceEvent) + assert isinstance(response, availability.Availability) assert response.name == "name_value" - assert response.event_type == "event_type_value" + assert response.state == availability.Availability.State.ACTIVE -def test_get_space_event_non_empty_request_with_auto_populated_field(): +def test_mark_as_away_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -14397,25 +14771,25 @@ def test_get_space_event_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = space_event.GetSpaceEventRequest( + request = availability.MarkAsAwayRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: + with mock.patch.object(type(client.transport.mark_as_away), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_space_event(request=request) + client.mark_as_away(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = space_event.GetSpaceEventRequest( + request_msg = availability.MarkAsAwayRequest( name="name_value", ) assert args[0] == request_msg -def test_get_space_event_use_cached_wrapped_rpc(): +def test_mark_as_away_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -14429,21 +14803,21 @@ def test_get_space_event_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_space_event in client._transport._wrapped_methods + assert client._transport.mark_as_away in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_space_event] = mock_rpc + client._transport._wrapped_methods[client._transport.mark_as_away] = mock_rpc request = {} - client.get_space_event(request) + client.mark_as_away(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_space_event(request) + client.mark_as_away(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -14451,7 +14825,7 @@ def test_get_space_event_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_space_event_async_use_cached_wrapped_rpc( +async def test_mark_as_away_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -14468,7 +14842,7 @@ async def test_get_space_event_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_space_event + client._client._transport.mark_as_away in client._client._transport._wrapped_methods ) @@ -14476,16 +14850,16 @@ async def test_get_space_event_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_space_event + client._client._transport.mark_as_away ] = mock_rpc request = {} - await client.get_space_event(request) + await client.mark_as_away(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_space_event(request) + await client.mark_as_away(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -14496,11 +14870,11 @@ async def test_get_space_event_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - space_event.GetSpaceEventRequest(), + availability.MarkAsAwayRequest(), {}, ], ) -async def test_get_space_event_async(request_type, transport: str = "grpc_asyncio"): +async def test_mark_as_away_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -14511,43 +14885,43 @@ async def test_get_space_event_async(request_type, transport: str = "grpc_asynci request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: + with mock.patch.object(type(client.transport.mark_as_away), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_event.SpaceEvent( + availability.Availability( name="name_value", - event_type="event_type_value", + state=availability.Availability.State.ACTIVE, ) ) - response = await client.get_space_event(request) + response = await client.mark_as_away(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = space_event.GetSpaceEventRequest() + request = availability.MarkAsAwayRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, space_event.SpaceEvent) + assert isinstance(response, availability.Availability) assert response.name == "name_value" - assert response.event_type == "event_type_value" + assert response.state == availability.Availability.State.ACTIVE -def test_get_space_event_field_headers(): +def test_mark_as_away_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = space_event.GetSpaceEventRequest() + request = availability.MarkAsAwayRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: - call.return_value = space_event.SpaceEvent() - client.get_space_event(request) + with mock.patch.object(type(client.transport.mark_as_away), "__call__") as call: + call.return_value = availability.Availability() + client.mark_as_away(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -14563,23 +14937,23 @@ def test_get_space_event_field_headers(): @pytest.mark.asyncio -async def test_get_space_event_field_headers_async(): +async def test_mark_as_away_field_headers_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = space_event.GetSpaceEventRequest() + request = availability.MarkAsAwayRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: + with mock.patch.object(type(client.transport.mark_as_away), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_event.SpaceEvent() + availability.Availability() ) - await client.get_space_event(request) + await client.mark_as_away(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -14594,96 +14968,277 @@ async def test_get_space_event_field_headers_async(): ) in kw["metadata"] -def test_get_space_event_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + availability.MarkAsDoNotDisturbRequest(), + {}, + ], +) +def test_mark_as_do_not_disturb(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_space_event), "__call__") as call: + with mock.patch.object( + type(client.transport.mark_as_do_not_disturb), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = space_event.SpaceEvent() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_space_event( + call.return_value = availability.Availability( name="name_value", + state=availability.Availability.State.ACTIVE, ) + response = client.mark_as_do_not_disturb(request) - # Establish that the underlying call was made with the expected - # request object values. + # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val + request = availability.MarkAsDoNotDisturbRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, availability.Availability) + assert response.name == "name_value" + assert response.state == availability.Availability.State.ACTIVE -def test_get_space_event_flattened_error(): +def test_mark_as_do_not_disturb_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_space_event( - space_event.GetSpaceEventRequest(), - name="name_value", - ) - - -@pytest.mark.asyncio -async def test_get_space_event_flattened_async(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = availability.MarkAsDoNotDisturbRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = space_event.SpaceEvent() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_event.SpaceEvent() + with mock.patch.object( + type(client.transport.mark_as_do_not_disturb), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_space_event( + client.mark_as_do_not_disturb(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = availability.MarkAsDoNotDisturbRequest( 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 + assert args[0] == request_msg -@pytest.mark.asyncio -async def test_get_space_event_flattened_error_async(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) +def test_mark_as_do_not_disturb_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_space_event( - space_event.GetSpaceEventRequest(), - name="name_value", + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.mark_as_do_not_disturb + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.mark_as_do_not_disturb] = ( + mock_rpc + ) + request = {} + client.mark_as_do_not_disturb(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.mark_as_do_not_disturb(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_mark_as_do_not_disturb_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.mark_as_do_not_disturb + in client._client._transport._wrapped_methods ) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.mark_as_do_not_disturb + ] = mock_rpc + + request = {} + await client.mark_as_do_not_disturb(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.mark_as_do_not_disturb(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio @pytest.mark.parametrize( "request_type", [ - space_event.ListSpaceEventsRequest(), + availability.MarkAsDoNotDisturbRequest(), {}, ], ) -def test_list_space_events(request_type, transport: str = "grpc"): +async def test_mark_as_do_not_disturb_async( + request_type, transport: str = "grpc_asyncio" +): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_as_do_not_disturb), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + availability.Availability( + name="name_value", + state=availability.Availability.State.ACTIVE, + ) + ) + response = await client.mark_as_do_not_disturb(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = availability.MarkAsDoNotDisturbRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, availability.Availability) + assert response.name == "name_value" + assert response.state == availability.Availability.State.ACTIVE + + +def test_mark_as_do_not_disturb_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = availability.MarkAsDoNotDisturbRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_as_do_not_disturb), "__call__" + ) as call: + call.return_value = availability.Availability() + client.mark_as_do_not_disturb(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_mark_as_do_not_disturb_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = availability.MarkAsDoNotDisturbRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mark_as_do_not_disturb), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + availability.Availability() + ) + await client.mark_as_do_not_disturb(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + gc_availability.UpdateAvailabilityRequest(), + {}, + ], +) +def test_update_availability(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14695,26 +15250,28 @@ def test_list_space_events(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_space_events), "__call__" + type(client.transport.update_availability), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = space_event.ListSpaceEventsResponse( - next_page_token="next_page_token_value", + call.return_value = gc_availability.Availability( + name="name_value", + state=gc_availability.Availability.State.ACTIVE, ) - response = client.list_space_events(request) + response = client.update_availability(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = space_event.ListSpaceEventsRequest() + request = gc_availability.UpdateAvailabilityRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSpaceEventsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, gc_availability.Availability) + assert response.name == "name_value" + assert response.state == gc_availability.Availability.State.ACTIVE -def test_list_space_events_non_empty_request_with_auto_populated_field(): +def test_update_availability_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -14725,31 +15282,23 @@ def test_list_space_events_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = space_event.ListSpaceEventsRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - ) + request = gc_availability.UpdateAvailabilityRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_space_events), "__call__" + type(client.transport.update_availability), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_space_events(request=request) + client.update_availability(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = space_event.ListSpaceEventsRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - ) + request_msg = gc_availability.UpdateAvailabilityRequest() assert args[0] == request_msg -def test_list_space_events_use_cached_wrapped_rpc(): +def test_update_availability_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -14763,23 +15312,25 @@ def test_list_space_events_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_space_events in client._transport._wrapped_methods + assert ( + client._transport.update_availability in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_space_events] = ( + client._transport._wrapped_methods[client._transport.update_availability] = ( mock_rpc ) request = {} - client.list_space_events(request) + client.update_availability(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_space_events(request) + client.update_availability(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -14787,7 +15338,7 @@ def test_list_space_events_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_space_events_async_use_cached_wrapped_rpc( +async def test_update_availability_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -14804,7 +15355,7 @@ async def test_list_space_events_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_space_events + client._client._transport.update_availability in client._client._transport._wrapped_methods ) @@ -14812,16 +15363,16 @@ async def test_list_space_events_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_space_events + client._client._transport.update_availability ] = mock_rpc request = {} - await client.list_space_events(request) + await client.update_availability(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_space_events(request) + await client.update_availability(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -14832,11 +15383,11 @@ async def test_list_space_events_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - space_event.ListSpaceEventsRequest(), + gc_availability.UpdateAvailabilityRequest(), {}, ], ) -async def test_list_space_events_async(request_type, transport: str = "grpc_asyncio"): +async def test_update_availability_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -14848,44 +15399,46 @@ async def test_list_space_events_async(request_type, transport: str = "grpc_asyn # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_space_events), "__call__" + type(client.transport.update_availability), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_event.ListSpaceEventsResponse( - next_page_token="next_page_token_value", + gc_availability.Availability( + name="name_value", + state=gc_availability.Availability.State.ACTIVE, ) ) - response = await client.list_space_events(request) + response = await client.update_availability(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = space_event.ListSpaceEventsRequest() + request = gc_availability.UpdateAvailabilityRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSpaceEventsAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, gc_availability.Availability) + assert response.name == "name_value" + assert response.state == gc_availability.Availability.State.ACTIVE -def test_list_space_events_field_headers(): +def test_update_availability_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = space_event.ListSpaceEventsRequest() + request = gc_availability.UpdateAvailabilityRequest() - request.parent = "parent_value" + request.availability.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_space_events), "__call__" + type(client.transport.update_availability), "__call__" ) as call: - call.return_value = space_event.ListSpaceEventsResponse() - client.list_space_events(request) + call.return_value = gc_availability.Availability() + client.update_availability(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -14896,30 +15449,30 @@ def test_list_space_events_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "availability.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_space_events_field_headers_async(): +async def test_update_availability_field_headers_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = space_event.ListSpaceEventsRequest() + request = gc_availability.UpdateAvailabilityRequest() - request.parent = "parent_value" + request.availability.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_space_events), "__call__" + type(client.transport.update_availability), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_event.ListSpaceEventsResponse() + gc_availability.Availability() ) - await client.list_space_events(request) + await client.update_availability(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -14930,41 +15483,41 @@ async def test_list_space_events_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "availability.name=name_value", ) in kw["metadata"] -def test_list_space_events_flattened(): +def test_update_availability_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_space_events), "__call__" + type(client.transport.update_availability), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = space_event.ListSpaceEventsResponse() + call.return_value = gc_availability.Availability() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_space_events( - parent="parent_value", - filter="filter_value", + client.update_availability( + availability=gc_availability.Availability(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].parent - mock_val = "parent_value" + arg = args[0].availability + mock_val = gc_availability.Availability(name="name_value") assert arg == mock_val - arg = args[0].filter - mock_val = "filter_value" + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_list_space_events_flattened_error(): +def test_update_availability_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -14972,50 +15525,50 @@ def test_list_space_events_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_space_events( - space_event.ListSpaceEventsRequest(), - parent="parent_value", - filter="filter_value", + client.update_availability( + gc_availability.UpdateAvailabilityRequest(), + availability=gc_availability.Availability(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_list_space_events_flattened_async(): +async def test_update_availability_flattened_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_space_events), "__call__" + type(client.transport.update_availability), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = space_event.ListSpaceEventsResponse() + call.return_value = gc_availability.Availability() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_event.ListSpaceEventsResponse() + gc_availability.Availability() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_space_events( - parent="parent_value", - filter="filter_value", + response = await client.update_availability( + availability=gc_availability.Availability(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].parent - mock_val = "parent_value" + arg = args[0].availability + mock_val = gc_availability.Availability(name="name_value") assert arg == mock_val - arg = args[0].filter - mock_val = "filter_value" + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_list_space_events_flattened_error_async(): +async def test_update_availability_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -15023,329 +15576,109 @@ async def test_list_space_events_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_space_events( - space_event.ListSpaceEventsRequest(), - parent="parent_value", - filter="filter_value", + await client.update_availability( + gc_availability.UpdateAvailabilityRequest(), + availability=gc_availability.Availability(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_list_space_events_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + space_event.GetSpaceEventRequest(), + {}, + ], +) +def test_get_space_event(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport=transport, ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_space_events), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - space_event.ListSpaceEventsResponse( - space_events=[ - space_event.SpaceEvent(), - space_event.SpaceEvent(), - space_event.SpaceEvent(), - ], - next_page_token="abc", - ), - space_event.ListSpaceEventsResponse( - space_events=[], - next_page_token="def", - ), - space_event.ListSpaceEventsResponse( - space_events=[ - space_event.SpaceEvent(), - ], - next_page_token="ghi", - ), - space_event.ListSpaceEventsResponse( - space_events=[ - space_event.SpaceEvent(), - space_event.SpaceEvent(), - ], - ), - RuntimeError, - ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = space_event.SpaceEvent( + name="name_value", + event_type="event_type_value", ) - pager = client.list_space_events(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout + response = client.get_space_event(request) - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = space_event.GetSpaceEventRequest() + assert args[0] == request - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, space_event.SpaceEvent) for i in results) + # Establish that the response is the type that we expect. + assert isinstance(response, space_event.SpaceEvent) + assert response.name == "name_value" + assert response.event_type == "event_type_value" -def test_list_space_events_pages(transport_name: str = "grpc"): +def test_get_space_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = space_event.GetSpaceEventRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_space_events), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - space_event.ListSpaceEventsResponse( - space_events=[ - space_event.SpaceEvent(), - space_event.SpaceEvent(), - space_event.SpaceEvent(), - ], - next_page_token="abc", - ), - space_event.ListSpaceEventsResponse( - space_events=[], - next_page_token="def", - ), - space_event.ListSpaceEventsResponse( - space_events=[ - space_event.SpaceEvent(), - ], - next_page_token="ghi", - ), - space_event.ListSpaceEventsResponse( - space_events=[ - space_event.SpaceEvent(), - space_event.SpaceEvent(), - ], - ), - RuntimeError, + with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - pages = list(client.list_space_events(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + client.get_space_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = space_event.GetSpaceEventRequest( + name="name_value", + ) + assert args[0] == request_msg -@pytest.mark.asyncio -async def test_list_space_events_async_pager(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_space_events), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - space_event.ListSpaceEventsResponse( - space_events=[ - space_event.SpaceEvent(), - space_event.SpaceEvent(), - space_event.SpaceEvent(), - ], - next_page_token="abc", - ), - space_event.ListSpaceEventsResponse( - space_events=[], - next_page_token="def", - ), - space_event.ListSpaceEventsResponse( - space_events=[ - space_event.SpaceEvent(), - ], - next_page_token="ghi", - ), - space_event.ListSpaceEventsResponse( - space_events=[ - space_event.SpaceEvent(), - space_event.SpaceEvent(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_space_events( - request={}, - ) - assert async_pager.next_page_token == "abc" - assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, space_event.SpaceEvent) for i in responses) - - -@pytest.mark.asyncio -async def test_list_space_events_async_pages(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_space_events), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - space_event.ListSpaceEventsResponse( - space_events=[ - space_event.SpaceEvent(), - space_event.SpaceEvent(), - space_event.SpaceEvent(), - ], - next_page_token="abc", - ), - space_event.ListSpaceEventsResponse( - space_events=[], - next_page_token="def", - ), - space_event.ListSpaceEventsResponse( - space_events=[ - space_event.SpaceEvent(), - ], - next_page_token="ghi", - ), - space_event.ListSpaceEventsResponse( - space_events=[ - space_event.SpaceEvent(), - space_event.SpaceEvent(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_space_events(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", - [ - space_notification_setting.GetSpaceNotificationSettingRequest(), - {}, - ], -) -def test_get_space_notification_setting(request_type, transport: str = "grpc"): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_space_notification_setting), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = space_notification_setting.SpaceNotificationSetting( - name="name_value", - notification_setting=space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, - mute_setting=space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, - ) - response = client.get_space_notification_setting(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = space_notification_setting.GetSpaceNotificationSettingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, space_notification_setting.SpaceNotificationSetting) - assert response.name == "name_value" - assert ( - response.notification_setting - == space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL - ) - assert ( - response.mute_setting - == space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED - ) - - -def test_get_space_notification_setting_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = space_notification_setting.GetSpaceNotificationSettingRequest( - name="name_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_space_notification_setting), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_space_notification_setting(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = space_notification_setting.GetSpaceNotificationSettingRequest( - name="name_value", - ) - assert args[0] == request_msg - - -def test_get_space_notification_setting_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) +def test_get_space_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_space_notification_setting - in client._transport._wrapped_methods - ) + assert client._transport.get_space_event in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.get_space_notification_setting - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_space_event] = mock_rpc request = {} - client.get_space_notification_setting(request) + client.get_space_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_space_notification_setting(request) + client.get_space_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -15353,7 +15686,7 @@ def test_get_space_notification_setting_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_space_notification_setting_async_use_cached_wrapped_rpc( +async def test_get_space_event_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -15370,7 +15703,7 @@ async def test_get_space_notification_setting_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_space_notification_setting + client._client._transport.get_space_event in client._client._transport._wrapped_methods ) @@ -15378,16 +15711,16 @@ async def test_get_space_notification_setting_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_space_notification_setting + client._client._transport.get_space_event ] = mock_rpc request = {} - await client.get_space_notification_setting(request) + await client.get_space_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_space_notification_setting(request) + await client.get_space_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -15398,13 +15731,11 @@ async def test_get_space_notification_setting_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - space_notification_setting.GetSpaceNotificationSettingRequest(), + space_event.GetSpaceEventRequest(), {}, ], ) -async def test_get_space_notification_setting_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_get_space_event_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -15415,55 +15746,43 @@ async def test_get_space_notification_setting_async( request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_space_notification_setting), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_notification_setting.SpaceNotificationSetting( + space_event.SpaceEvent( name="name_value", - notification_setting=space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, - mute_setting=space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, + event_type="event_type_value", ) ) - response = await client.get_space_notification_setting(request) + response = await client.get_space_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = space_notification_setting.GetSpaceNotificationSettingRequest() + request = space_event.GetSpaceEventRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, space_notification_setting.SpaceNotificationSetting) + assert isinstance(response, space_event.SpaceEvent) assert response.name == "name_value" - assert ( - response.notification_setting - == space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL - ) - assert ( - response.mute_setting - == space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED - ) + assert response.event_type == "event_type_value" -def test_get_space_notification_setting_field_headers(): +def test_get_space_event_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = space_notification_setting.GetSpaceNotificationSettingRequest() + request = space_event.GetSpaceEventRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_space_notification_setting), "__call__" - ) as call: - call.return_value = space_notification_setting.SpaceNotificationSetting() - client.get_space_notification_setting(request) + with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: + call.return_value = space_event.SpaceEvent() + client.get_space_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -15479,25 +15798,23 @@ def test_get_space_notification_setting_field_headers(): @pytest.mark.asyncio -async def test_get_space_notification_setting_field_headers_async(): +async def test_get_space_event_field_headers_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = space_notification_setting.GetSpaceNotificationSettingRequest() + request = space_event.GetSpaceEventRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_space_notification_setting), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_notification_setting.SpaceNotificationSetting() + space_event.SpaceEvent() ) - await client.get_space_notification_setting(request) + await client.get_space_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -15512,20 +15829,18 @@ async def test_get_space_notification_setting_field_headers_async(): ) in kw["metadata"] -def test_get_space_notification_setting_flattened(): +def test_get_space_event_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_space_notification_setting), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = space_notification_setting.SpaceNotificationSetting() + call.return_value = space_event.SpaceEvent() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_space_notification_setting( + client.get_space_event( name="name_value", ) @@ -15538,7 +15853,7 @@ def test_get_space_notification_setting_flattened(): assert arg == mock_val -def test_get_space_notification_setting_flattened_error(): +def test_get_space_event_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -15546,31 +15861,29 @@ def test_get_space_notification_setting_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_space_notification_setting( - space_notification_setting.GetSpaceNotificationSettingRequest(), + client.get_space_event( + space_event.GetSpaceEventRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_space_notification_setting_flattened_async(): +async def test_get_space_event_flattened_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_space_notification_setting), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_space_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = space_notification_setting.SpaceNotificationSetting() + call.return_value = space_event.SpaceEvent() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - space_notification_setting.SpaceNotificationSetting() + space_event.SpaceEvent() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_space_notification_setting( + response = await client.get_space_event( name="name_value", ) @@ -15584,7 +15897,7 @@ async def test_get_space_notification_setting_flattened_async(): @pytest.mark.asyncio -async def test_get_space_notification_setting_flattened_error_async(): +async def test_get_space_event_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -15592,8 +15905,8 @@ async def test_get_space_notification_setting_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_space_notification_setting( - space_notification_setting.GetSpaceNotificationSettingRequest(), + await client.get_space_event( + space_event.GetSpaceEventRequest(), name="name_value", ) @@ -15601,11 +15914,11 @@ async def test_get_space_notification_setting_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - gc_space_notification_setting.UpdateSpaceNotificationSettingRequest(), + space_event.ListSpaceEventsRequest(), {}, ], ) -def test_update_space_notification_setting(request_type, transport: str = "grpc"): +def test_list_space_events(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15617,36 +15930,26 @@ def test_update_space_notification_setting(request_type, transport: str = "grpc" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_space_notification_setting), "__call__" + type(client.transport.list_space_events), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gc_space_notification_setting.SpaceNotificationSetting( - name="name_value", - notification_setting=gc_space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, - mute_setting=gc_space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, + call.return_value = space_event.ListSpaceEventsResponse( + next_page_token="next_page_token_value", ) - response = client.update_space_notification_setting(request) + response = client.list_space_events(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() + request = space_event.ListSpaceEventsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gc_space_notification_setting.SpaceNotificationSetting) - assert response.name == "name_value" - assert ( - response.notification_setting - == gc_space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL - ) - assert ( - response.mute_setting - == gc_space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED - ) + assert isinstance(response, pagers.ListSpaceEventsPager) + assert response.next_page_token == "next_page_token_value" -def test_update_space_notification_setting_non_empty_request_with_auto_populated_field(): +def test_list_space_events_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -15657,25 +15960,31 @@ def test_update_space_notification_setting_non_empty_request_with_auto_populated # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() + request = space_event.ListSpaceEventsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_space_notification_setting), "__call__" + type(client.transport.list_space_events), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_space_notification_setting(request=request) + client.list_space_events(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = ( - gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() + request_msg = space_event.ListSpaceEventsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", ) assert args[0] == request_msg -def test_update_space_notification_setting_use_cached_wrapped_rpc(): +def test_list_space_events_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -15689,26 +15998,23 @@ def test_update_space_notification_setting_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_space_notification_setting - in client._transport._wrapped_methods - ) + assert client._transport.list_space_events in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.update_space_notification_setting - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_space_events] = ( + mock_rpc + ) request = {} - client.update_space_notification_setting(request) + client.list_space_events(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_space_notification_setting(request) + client.list_space_events(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -15716,7 +16022,7 @@ def test_update_space_notification_setting_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_space_notification_setting_async_use_cached_wrapped_rpc( +async def test_list_space_events_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -15733,7 +16039,7 @@ async def test_update_space_notification_setting_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_space_notification_setting + client._client._transport.list_space_events in client._client._transport._wrapped_methods ) @@ -15741,16 +16047,16 @@ async def test_update_space_notification_setting_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_space_notification_setting + client._client._transport.list_space_events ] = mock_rpc request = {} - await client.update_space_notification_setting(request) + await client.list_space_events(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.update_space_notification_setting(request) + await client.list_space_events(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -15761,13 +16067,11 @@ async def test_update_space_notification_setting_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - gc_space_notification_setting.UpdateSpaceNotificationSettingRequest(), + space_event.ListSpaceEventsRequest(), {}, ], ) -async def test_update_space_notification_setting_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_list_space_events_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -15779,54 +16083,44 @@ async def test_update_space_notification_setting_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_space_notification_setting), "__call__" + type(client.transport.list_space_events), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_space_notification_setting.SpaceNotificationSetting( - name="name_value", - notification_setting=gc_space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, - mute_setting=gc_space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, + space_event.ListSpaceEventsResponse( + next_page_token="next_page_token_value", ) ) - response = await client.update_space_notification_setting(request) + response = await client.list_space_events(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() + request = space_event.ListSpaceEventsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gc_space_notification_setting.SpaceNotificationSetting) - assert response.name == "name_value" - assert ( - response.notification_setting - == gc_space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL - ) - assert ( - response.mute_setting - == gc_space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED - ) + assert isinstance(response, pagers.ListSpaceEventsAsyncPager) + assert response.next_page_token == "next_page_token_value" -def test_update_space_notification_setting_field_headers(): +def test_list_space_events_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() + request = space_event.ListSpaceEventsRequest() - request.space_notification_setting.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_space_notification_setting), "__call__" + type(client.transport.list_space_events), "__call__" ) as call: - call.return_value = gc_space_notification_setting.SpaceNotificationSetting() - client.update_space_notification_setting(request) + call.return_value = space_event.ListSpaceEventsResponse() + client.list_space_events(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -15837,30 +16131,30 @@ def test_update_space_notification_setting_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "space_notification_setting.name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_space_notification_setting_field_headers_async(): +async def test_list_space_events_field_headers_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() + request = space_event.ListSpaceEventsRequest() - request.space_notification_setting.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_space_notification_setting), "__call__" + type(client.transport.list_space_events), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_space_notification_setting.SpaceNotificationSetting() + space_event.ListSpaceEventsResponse() ) - await client.update_space_notification_setting(request) + await client.list_space_events(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -15871,45 +16165,41 @@ async def test_update_space_notification_setting_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "space_notification_setting.name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_update_space_notification_setting_flattened(): +def test_list_space_events_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_space_notification_setting), "__call__" + type(client.transport.list_space_events), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gc_space_notification_setting.SpaceNotificationSetting() + call.return_value = space_event.ListSpaceEventsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_space_notification_setting( - space_notification_setting=gc_space_notification_setting.SpaceNotificationSetting( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_space_events( + parent="parent_value", + filter="filter_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].space_notification_setting - mock_val = gc_space_notification_setting.SpaceNotificationSetting( - name="name_value" - ) + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].filter + mock_val = "filter_value" assert arg == mock_val -def test_update_space_notification_setting_flattened_error(): +def test_list_space_events_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -15917,56 +16207,50 @@ def test_update_space_notification_setting_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_space_notification_setting( - gc_space_notification_setting.UpdateSpaceNotificationSettingRequest(), - space_notification_setting=gc_space_notification_setting.SpaceNotificationSetting( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_space_events( + space_event.ListSpaceEventsRequest(), + parent="parent_value", + filter="filter_value", ) @pytest.mark.asyncio -async def test_update_space_notification_setting_flattened_async(): +async def test_list_space_events_flattened_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_space_notification_setting), "__call__" + type(client.transport.list_space_events), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gc_space_notification_setting.SpaceNotificationSetting() + call.return_value = space_event.ListSpaceEventsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_space_notification_setting.SpaceNotificationSetting() + space_event.ListSpaceEventsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_space_notification_setting( - space_notification_setting=gc_space_notification_setting.SpaceNotificationSetting( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.list_space_events( + parent="parent_value", + filter="filter_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].space_notification_setting - mock_val = gc_space_notification_setting.SpaceNotificationSetting( - name="name_value" - ) + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].filter + mock_val = "filter_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_space_notification_setting_flattened_error_async(): +async def test_list_space_events_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -15974,58 +16258,265 @@ async def test_update_space_notification_setting_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_space_notification_setting( - gc_space_notification_setting.UpdateSpaceNotificationSettingRequest(), - space_notification_setting=gc_space_notification_setting.SpaceNotificationSetting( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.list_space_events( + space_event.ListSpaceEventsRequest(), + parent="parent_value", + filter="filter_value", ) -@pytest.mark.parametrize( - "request_type", - [ - gc_section.CreateSectionRequest(), - {}, - ], -) -def test_create_section(request_type, transport: str = "grpc"): +def test_list_space_events_pager(transport_name: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_section), "__call__") as call: + with mock.patch.object( + type(client.transport.list_space_events), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + space_event.ListSpaceEventsResponse( + space_events=[ + space_event.SpaceEvent(), + space_event.SpaceEvent(), + space_event.SpaceEvent(), + ], + next_page_token="abc", + ), + space_event.ListSpaceEventsResponse( + space_events=[], + next_page_token="def", + ), + space_event.ListSpaceEventsResponse( + space_events=[ + space_event.SpaceEvent(), + ], + next_page_token="ghi", + ), + space_event.ListSpaceEventsResponse( + space_events=[ + space_event.SpaceEvent(), + space_event.SpaceEvent(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_space_events(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, space_event.SpaceEvent) for i in results) + + +def test_list_space_events_pages(transport_name: str = "grpc"): + client = ChatServiceClient( + 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_space_events), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + space_event.ListSpaceEventsResponse( + space_events=[ + space_event.SpaceEvent(), + space_event.SpaceEvent(), + space_event.SpaceEvent(), + ], + next_page_token="abc", + ), + space_event.ListSpaceEventsResponse( + space_events=[], + next_page_token="def", + ), + space_event.ListSpaceEventsResponse( + space_events=[ + space_event.SpaceEvent(), + ], + next_page_token="ghi", + ), + space_event.ListSpaceEventsResponse( + space_events=[ + space_event.SpaceEvent(), + space_event.SpaceEvent(), + ], + ), + RuntimeError, + ) + pages = list(client.list_space_events(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_space_events_async_pager(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_space_events), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + space_event.ListSpaceEventsResponse( + space_events=[ + space_event.SpaceEvent(), + space_event.SpaceEvent(), + space_event.SpaceEvent(), + ], + next_page_token="abc", + ), + space_event.ListSpaceEventsResponse( + space_events=[], + next_page_token="def", + ), + space_event.ListSpaceEventsResponse( + space_events=[ + space_event.SpaceEvent(), + ], + next_page_token="ghi", + ), + space_event.ListSpaceEventsResponse( + space_events=[ + space_event.SpaceEvent(), + space_event.SpaceEvent(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_space_events( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, space_event.SpaceEvent) for i in responses) + + +@pytest.mark.asyncio +async def test_list_space_events_async_pages(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_space_events), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + space_event.ListSpaceEventsResponse( + space_events=[ + space_event.SpaceEvent(), + space_event.SpaceEvent(), + space_event.SpaceEvent(), + ], + next_page_token="abc", + ), + space_event.ListSpaceEventsResponse( + space_events=[], + next_page_token="def", + ), + space_event.ListSpaceEventsResponse( + space_events=[ + space_event.SpaceEvent(), + ], + next_page_token="ghi", + ), + space_event.ListSpaceEventsResponse( + space_events=[ + space_event.SpaceEvent(), + space_event.SpaceEvent(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_space_events(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", + [ + space_notification_setting.GetSpaceNotificationSettingRequest(), + {}, + ], +) +def test_get_space_notification_setting(request_type, transport: str = "grpc"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_space_notification_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = gc_section.Section( + call.return_value = space_notification_setting.SpaceNotificationSetting( name="name_value", - display_name="display_name_value", - sort_order=1091, - type_=gc_section.Section.SectionType.CUSTOM_SECTION, + notification_setting=space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, + mute_setting=space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, ) - response = client.create_section(request) + response = client.get_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = gc_section.CreateSectionRequest() + request = space_notification_setting.GetSpaceNotificationSettingRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gc_section.Section) + assert isinstance(response, space_notification_setting.SpaceNotificationSetting) assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.sort_order == 1091 - assert response.type_ == gc_section.Section.SectionType.CUSTOM_SECTION + assert ( + response.notification_setting + == space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL + ) + assert ( + response.mute_setting + == space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED + ) -def test_create_section_non_empty_request_with_auto_populated_field(): +def test_get_space_notification_setting_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -16036,25 +16527,27 @@ def test_create_section_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = gc_section.CreateSectionRequest( - parent="parent_value", + request = space_notification_setting.GetSpaceNotificationSettingRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_section), "__call__") as call: + with mock.patch.object( + type(client.transport.get_space_notification_setting), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_section(request=request) + client.get_space_notification_setting(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = gc_section.CreateSectionRequest( - parent="parent_value", + request_msg = space_notification_setting.GetSpaceNotificationSettingRequest( + name="name_value", ) assert args[0] == request_msg -def test_create_section_use_cached_wrapped_rpc(): +def test_get_space_notification_setting_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -16068,21 +16561,26 @@ def test_create_section_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_section in client._transport._wrapped_methods + assert ( + client._transport.get_space_notification_setting + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_section] = mock_rpc + client._transport._wrapped_methods[ + client._transport.get_space_notification_setting + ] = mock_rpc request = {} - client.create_section(request) + client.get_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_section(request) + client.get_space_notification_setting(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -16090,7 +16588,7 @@ def test_create_section_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_section_async_use_cached_wrapped_rpc( +async def test_get_space_notification_setting_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -16107,7 +16605,7 @@ async def test_create_section_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_section + client._client._transport.get_space_notification_setting in client._client._transport._wrapped_methods ) @@ -16115,16 +16613,16 @@ async def test_create_section_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_section + client._client._transport.get_space_notification_setting ] = mock_rpc request = {} - await client.create_section(request) + await client.get_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.create_section(request) + await client.get_space_notification_setting(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -16135,11 +16633,13 @@ async def test_create_section_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - gc_section.CreateSectionRequest(), + space_notification_setting.GetSpaceNotificationSettingRequest(), {}, ], ) -async def test_create_section_async(request_type, transport: str = "grpc_asyncio"): +async def test_get_space_notification_setting_async( + request_type, transport: str = "grpc_asyncio" +): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -16150,47 +16650,55 @@ async def test_create_section_async(request_type, transport: str = "grpc_asyncio request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_section), "__call__") as call: + with mock.patch.object( + type(client.transport.get_space_notification_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gc_section.Section( + space_notification_setting.SpaceNotificationSetting( name="name_value", - display_name="display_name_value", - sort_order=1091, - type_=gc_section.Section.SectionType.CUSTOM_SECTION, + notification_setting=space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, + mute_setting=space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, ) ) - response = await client.create_section(request) + response = await client.get_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = gc_section.CreateSectionRequest() + request = space_notification_setting.GetSpaceNotificationSettingRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gc_section.Section) + assert isinstance(response, space_notification_setting.SpaceNotificationSetting) assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.sort_order == 1091 - assert response.type_ == gc_section.Section.SectionType.CUSTOM_SECTION + assert ( + response.notification_setting + == space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL + ) + assert ( + response.mute_setting + == space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED + ) -def test_create_section_field_headers(): +def test_get_space_notification_setting_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = gc_section.CreateSectionRequest() + request = space_notification_setting.GetSpaceNotificationSettingRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_section), "__call__") as call: - call.return_value = gc_section.Section() - client.create_section(request) + with mock.patch.object( + type(client.transport.get_space_notification_setting), "__call__" + ) as call: + call.return_value = space_notification_setting.SpaceNotificationSetting() + client.get_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -16201,26 +16709,30 @@ def test_create_section_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_section_field_headers_async(): +async def test_get_space_notification_setting_field_headers_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = gc_section.CreateSectionRequest() + request = space_notification_setting.GetSpaceNotificationSettingRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_section), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_section.Section()) - await client.create_section(request) + with mock.patch.object( + type(client.transport.get_space_notification_setting), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space_notification_setting.SpaceNotificationSetting() + ) + await client.get_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -16231,39 +16743,37 @@ async def test_create_section_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_create_section_flattened(): +def test_get_space_notification_setting_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_section), "__call__") as call: + with mock.patch.object( + type(client.transport.get_space_notification_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = gc_section.Section() + call.return_value = space_notification_setting.SpaceNotificationSetting() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_section( - parent="parent_value", - section=gc_section.Section(name="name_value"), + client.get_space_notification_setting( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].section - mock_val = gc_section.Section(name="name_value") + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_create_section_flattened_error(): +def test_get_space_notification_setting_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -16271,46 +16781,45 @@ def test_create_section_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_section( - gc_section.CreateSectionRequest(), - parent="parent_value", - section=gc_section.Section(name="name_value"), + client.get_space_notification_setting( + space_notification_setting.GetSpaceNotificationSettingRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_create_section_flattened_async(): +async def test_get_space_notification_setting_flattened_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_section), "__call__") as call: + with mock.patch.object( + type(client.transport.get_space_notification_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = gc_section.Section() + call.return_value = space_notification_setting.SpaceNotificationSetting() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_section.Section()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space_notification_setting.SpaceNotificationSetting() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_section( - parent="parent_value", - section=gc_section.Section(name="name_value"), + response = await client.get_space_notification_setting( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].section - mock_val = gc_section.Section(name="name_value") + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_section_flattened_error_async(): +async def test_get_space_notification_setting_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -16318,21 +16827,20 @@ async def test_create_section_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_section( - gc_section.CreateSectionRequest(), - parent="parent_value", - section=gc_section.Section(name="name_value"), + await client.get_space_notification_setting( + space_notification_setting.GetSpaceNotificationSettingRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - section.DeleteSectionRequest(), + gc_space_notification_setting.UpdateSpaceNotificationSettingRequest(), {}, ], ) -def test_delete_section(request_type, transport: str = "grpc"): +def test_update_space_notification_setting(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16343,22 +16851,37 @@ def test_delete_section(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_section), "__call__") as call: + with mock.patch.object( + type(client.transport.update_space_notification_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_section(request) + call.return_value = gc_space_notification_setting.SpaceNotificationSetting( + name="name_value", + notification_setting=gc_space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, + mute_setting=gc_space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, + ) + response = client.update_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = section.DeleteSectionRequest() + request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, gc_space_notification_setting.SpaceNotificationSetting) + assert response.name == "name_value" + assert ( + response.notification_setting + == gc_space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL + ) + assert ( + response.mute_setting + == gc_space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED + ) -def test_delete_section_non_empty_request_with_auto_populated_field(): +def test_update_space_notification_setting_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -16369,25 +16892,25 @@ def test_delete_section_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = section.DeleteSectionRequest( - name="name_value", - ) + request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_section), "__call__") as call: + with mock.patch.object( + type(client.transport.update_space_notification_setting), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_section(request=request) + client.update_space_notification_setting(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = section.DeleteSectionRequest( - name="name_value", + request_msg = ( + gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() ) assert args[0] == request_msg -def test_delete_section_use_cached_wrapped_rpc(): +def test_update_space_notification_setting_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -16401,21 +16924,26 @@ def test_delete_section_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_section in client._transport._wrapped_methods + assert ( + client._transport.update_space_notification_setting + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_section] = mock_rpc + client._transport._wrapped_methods[ + client._transport.update_space_notification_setting + ] = mock_rpc request = {} - client.delete_section(request) + client.update_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_section(request) + client.update_space_notification_setting(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -16423,7 +16951,7 @@ def test_delete_section_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_section_async_use_cached_wrapped_rpc( +async def test_update_space_notification_setting_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -16440,7 +16968,7 @@ async def test_delete_section_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_section + client._client._transport.update_space_notification_setting in client._client._transport._wrapped_methods ) @@ -16448,16 +16976,16 @@ async def test_delete_section_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_section + client._client._transport.update_space_notification_setting ] = mock_rpc request = {} - await client.delete_section(request) + await client.update_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.delete_section(request) + await client.update_space_notification_setting(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -16468,11 +16996,13 @@ async def test_delete_section_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - section.DeleteSectionRequest(), + gc_space_notification_setting.UpdateSpaceNotificationSettingRequest(), {}, ], ) -async def test_delete_section_async(request_type, transport: str = "grpc_asyncio"): +async def test_update_space_notification_setting_async( + request_type, transport: str = "grpc_asyncio" +): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -16483,36 +17013,55 @@ async def test_delete_section_async(request_type, transport: str = "grpc_asyncio request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_section), "__call__") as call: + with mock.patch.object( + type(client.transport.update_space_notification_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_section(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_space_notification_setting.SpaceNotificationSetting( + name="name_value", + notification_setting=gc_space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL, + mute_setting=gc_space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED, + ) + ) + response = await client.update_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = section.DeleteSectionRequest() + request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_section_field_headers(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + assert isinstance(response, gc_space_notification_setting.SpaceNotificationSetting) + assert response.name == "name_value" + assert ( + response.notification_setting + == gc_space_notification_setting.SpaceNotificationSetting.NotificationSetting.ALL + ) + assert ( + response.mute_setting + == gc_space_notification_setting.SpaceNotificationSetting.MuteSetting.UNMUTED + ) + + +def test_update_space_notification_setting_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = section.DeleteSectionRequest() + request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() - request.name = "name_value" + request.space_notification_setting.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_section), "__call__") as call: - call.return_value = None - client.delete_section(request) + with mock.patch.object( + type(client.transport.update_space_notification_setting), "__call__" + ) as call: + call.return_value = gc_space_notification_setting.SpaceNotificationSetting() + client.update_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -16523,26 +17072,30 @@ def test_delete_section_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "space_notification_setting.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_delete_section_field_headers_async(): +async def test_update_space_notification_setting_field_headers_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = section.DeleteSectionRequest() + request = gc_space_notification_setting.UpdateSpaceNotificationSettingRequest() - request.name = "name_value" + request.space_notification_setting.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_section), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_section(request) + with mock.patch.object( + type(client.transport.update_space_notification_setting), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_space_notification_setting.SpaceNotificationSetting() + ) + await client.update_space_notification_setting(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -16553,35 +17106,45 @@ async def test_delete_section_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "space_notification_setting.name=name_value", ) in kw["metadata"] -def test_delete_section_flattened(): +def test_update_space_notification_setting_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_section), "__call__") as call: + with mock.patch.object( + type(client.transport.update_space_notification_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = gc_space_notification_setting.SpaceNotificationSetting() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_section( - name="name_value", + client.update_space_notification_setting( + space_notification_setting=gc_space_notification_setting.SpaceNotificationSetting( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].space_notification_setting + mock_val = gc_space_notification_setting.SpaceNotificationSetting( + 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_delete_section_flattened_error(): +def test_update_space_notification_setting_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -16589,41 +17152,56 @@ def test_delete_section_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_section( - section.DeleteSectionRequest(), - name="name_value", + client.update_space_notification_setting( + gc_space_notification_setting.UpdateSpaceNotificationSettingRequest(), + space_notification_setting=gc_space_notification_setting.SpaceNotificationSetting( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_delete_section_flattened_async(): +async def test_update_space_notification_setting_flattened_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_section), "__call__") as call: + with mock.patch.object( + type(client.transport.update_space_notification_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = gc_space_notification_setting.SpaceNotificationSetting() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_space_notification_setting.SpaceNotificationSetting() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_section( - name="name_value", + response = await client.update_space_notification_setting( + space_notification_setting=gc_space_notification_setting.SpaceNotificationSetting( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].space_notification_setting + mock_val = gc_space_notification_setting.SpaceNotificationSetting( + 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_delete_section_flattened_error_async(): +async def test_update_space_notification_setting_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -16631,20 +17209,23 @@ async def test_delete_section_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_section( - section.DeleteSectionRequest(), - name="name_value", + await client.update_space_notification_setting( + gc_space_notification_setting.UpdateSpaceNotificationSettingRequest(), + space_notification_setting=gc_space_notification_setting.SpaceNotificationSetting( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - gc_section.UpdateSectionRequest(), + gc_section.CreateSectionRequest(), {}, ], ) -def test_update_section(request_type, transport: str = "grpc"): +def test_create_section(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16655,7 +17236,7 @@ def test_update_section(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_section), "__call__") as call: + with mock.patch.object(type(client.transport.create_section), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gc_section.Section( name="name_value", @@ -16663,12 +17244,12 @@ def test_update_section(request_type, transport: str = "grpc"): sort_order=1091, type_=gc_section.Section.SectionType.CUSTOM_SECTION, ) - response = client.update_section(request) + response = client.create_section(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = gc_section.UpdateSectionRequest() + request = gc_section.CreateSectionRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -16679,7 +17260,7 @@ def test_update_section(request_type, transport: str = "grpc"): assert response.type_ == gc_section.Section.SectionType.CUSTOM_SECTION -def test_update_section_non_empty_request_with_auto_populated_field(): +def test_create_section_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -16690,21 +17271,25 @@ def test_update_section_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = gc_section.UpdateSectionRequest() + request = gc_section.CreateSectionRequest( + parent="parent_value", + ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_section), "__call__") as call: + with mock.patch.object(type(client.transport.create_section), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_section(request=request) + client.create_section(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = gc_section.UpdateSectionRequest() + request_msg = gc_section.CreateSectionRequest( + parent="parent_value", + ) assert args[0] == request_msg -def test_update_section_use_cached_wrapped_rpc(): +def test_create_section_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -16718,21 +17303,21 @@ def test_update_section_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_section in client._transport._wrapped_methods + assert client._transport.create_section in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_section] = mock_rpc + client._transport._wrapped_methods[client._transport.create_section] = mock_rpc request = {} - client.update_section(request) + client.create_section(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_section(request) + client.create_section(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -16740,7 +17325,7 @@ def test_update_section_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_section_async_use_cached_wrapped_rpc( +async def test_create_section_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -16757,7 +17342,7 @@ async def test_update_section_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_section + client._client._transport.create_section in client._client._transport._wrapped_methods ) @@ -16765,16 +17350,16 @@ async def test_update_section_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_section + client._client._transport.create_section ] = mock_rpc request = {} - await client.update_section(request) + await client.create_section(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.update_section(request) + await client.create_section(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -16785,11 +17370,11 @@ async def test_update_section_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - gc_section.UpdateSectionRequest(), + gc_section.CreateSectionRequest(), {}, ], ) -async def test_update_section_async(request_type, transport: str = "grpc_asyncio"): +async def test_create_section_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -16800,7 +17385,7 @@ async def test_update_section_async(request_type, transport: str = "grpc_asyncio request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_section), "__call__") as call: + with mock.patch.object(type(client.transport.create_section), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gc_section.Section( @@ -16810,12 +17395,12 @@ async def test_update_section_async(request_type, transport: str = "grpc_asyncio type_=gc_section.Section.SectionType.CUSTOM_SECTION, ) ) - response = await client.update_section(request) + response = await client.create_section(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = gc_section.UpdateSectionRequest() + request = gc_section.CreateSectionRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -16826,21 +17411,21 @@ async def test_update_section_async(request_type, transport: str = "grpc_asyncio assert response.type_ == gc_section.Section.SectionType.CUSTOM_SECTION -def test_update_section_field_headers(): +def test_create_section_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = gc_section.UpdateSectionRequest() + request = gc_section.CreateSectionRequest() - request.section.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_section), "__call__") as call: + with mock.patch.object(type(client.transport.create_section), "__call__") as call: call.return_value = gc_section.Section() - client.update_section(request) + client.create_section(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -16851,26 +17436,26 @@ def test_update_section_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "section.name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_section_field_headers_async(): +async def test_create_section_field_headers_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = gc_section.UpdateSectionRequest() + request = gc_section.CreateSectionRequest() - request.section.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_section), "__call__") as call: + with mock.patch.object(type(client.transport.create_section), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_section.Section()) - await client.update_section(request) + await client.create_section(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -16881,39 +17466,39 @@ async def test_update_section_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "section.name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_update_section_flattened(): +def test_create_section_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_section), "__call__") as call: + with mock.patch.object(type(client.transport.create_section), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gc_section.Section() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_section( + client.create_section( + parent="parent_value", section=gc_section.Section(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].parent + mock_val = "parent_value" + assert arg == mock_val arg = args[0].section mock_val = gc_section.Section(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_section_flattened_error(): +def test_create_section_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -16921,46 +17506,46 @@ def test_update_section_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_section( - gc_section.UpdateSectionRequest(), + client.create_section( + gc_section.CreateSectionRequest(), + parent="parent_value", section=gc_section.Section(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_update_section_flattened_async(): +async def test_create_section_flattened_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_section), "__call__") as call: + with mock.patch.object(type(client.transport.create_section), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gc_section.Section() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_section.Section()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_section( + response = await client.create_section( + parent="parent_value", section=gc_section.Section(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].parent + mock_val = "parent_value" + assert arg == mock_val arg = args[0].section mock_val = gc_section.Section(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_section_flattened_error_async(): +async def test_create_section_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -16968,21 +17553,21 @@ async def test_update_section_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_section( - gc_section.UpdateSectionRequest(), + await client.create_section( + gc_section.CreateSectionRequest(), + parent="parent_value", section=gc_section.Section(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - section.ListSectionsRequest(), + section.DeleteSectionRequest(), {}, ], ) -def test_list_sections(request_type, transport: str = "grpc"): +def test_delete_section(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16993,25 +17578,22 @@ def test_list_sections(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_sections), "__call__") as call: + with mock.patch.object(type(client.transport.delete_section), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = section.ListSectionsResponse( - next_page_token="next_page_token_value", - ) - response = client.list_sections(request) + call.return_value = None + response = client.delete_section(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = section.ListSectionsRequest() + request = section.DeleteSectionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSectionsPager) - assert response.next_page_token == "next_page_token_value" + assert response is None -def test_list_sections_non_empty_request_with_auto_populated_field(): +def test_delete_section_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -17022,27 +17604,25 @@ def test_list_sections_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = section.ListSectionsRequest( - parent="parent_value", - page_token="page_token_value", + request = section.DeleteSectionRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_sections), "__call__") as call: + with mock.patch.object(type(client.transport.delete_section), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_sections(request=request) + client.delete_section(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = section.ListSectionsRequest( - parent="parent_value", - page_token="page_token_value", + request_msg = section.DeleteSectionRequest( + name="name_value", ) assert args[0] == request_msg -def test_list_sections_use_cached_wrapped_rpc(): +def test_delete_section_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -17056,21 +17636,21 @@ def test_list_sections_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_sections in client._transport._wrapped_methods + assert client._transport.delete_section in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_sections] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_section] = mock_rpc request = {} - client.list_sections(request) + client.delete_section(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_sections(request) + client.delete_section(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -17078,7 +17658,7 @@ def test_list_sections_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_sections_async_use_cached_wrapped_rpc( +async def test_delete_section_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -17095,7 +17675,7 @@ async def test_list_sections_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_sections + client._client._transport.delete_section in client._client._transport._wrapped_methods ) @@ -17103,16 +17683,16 @@ async def test_list_sections_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_sections + client._client._transport.delete_section ] = mock_rpc request = {} - await client.list_sections(request) + await client.delete_section(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_sections(request) + await client.delete_section(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -17123,11 +17703,11 @@ async def test_list_sections_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - section.ListSectionsRequest(), + section.DeleteSectionRequest(), {}, ], ) -async def test_list_sections_async(request_type, transport: str = "grpc_asyncio"): +async def test_delete_section_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -17138,41 +17718,36 @@ async def test_list_sections_async(request_type, transport: str = "grpc_asyncio" request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_sections), "__call__") as call: + with mock.patch.object(type(client.transport.delete_section), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - section.ListSectionsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_sections(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_section(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = section.ListSectionsRequest() + request = section.DeleteSectionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSectionsAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert response is None -def test_list_sections_field_headers(): +def test_delete_section_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = section.ListSectionsRequest() + request = section.DeleteSectionRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_sections), "__call__") as call: - call.return_value = section.ListSectionsResponse() - client.list_sections(request) + with mock.patch.object(type(client.transport.delete_section), "__call__") as call: + call.return_value = None + client.delete_section(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -17183,28 +17758,26 @@ def test_list_sections_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_sections_field_headers_async(): +async def test_delete_section_field_headers_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = section.ListSectionsRequest() + request = section.DeleteSectionRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_sections), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - section.ListSectionsResponse() - ) - await client.list_sections(request) + with mock.patch.object(type(client.transport.delete_section), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_section(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -17215,35 +17788,35 @@ async def test_list_sections_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_list_sections_flattened(): +def test_delete_section_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_sections), "__call__") as call: + with mock.patch.object(type(client.transport.delete_section), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = section.ListSectionsResponse() + call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_sections( - parent="parent_value", + client.delete_section( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_list_sections_flattened_error(): +def test_delete_section_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -17251,43 +17824,41 @@ def test_list_sections_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_sections( - section.ListSectionsRequest(), - parent="parent_value", + client.delete_section( + section.DeleteSectionRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_list_sections_flattened_async(): +async def test_delete_section_flattened_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_sections), "__call__") as call: + with mock.patch.object(type(client.transport.delete_section), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = section.ListSectionsResponse() + call.return_value = None - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - section.ListSectionsResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_sections( - parent="parent_value", + response = await client.delete_section( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_list_sections_flattened_error_async(): +async def test_delete_section_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -17295,270 +17866,80 @@ async def test_list_sections_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_sections( - section.ListSectionsRequest(), - parent="parent_value", + await client.delete_section( + section.DeleteSectionRequest(), + name="name_value", ) -def test_list_sections_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + gc_section.UpdateSectionRequest(), + {}, + ], +) +def test_update_section(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport=transport, ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_sections), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - section.ListSectionsResponse( - sections=[ - section.Section(), - section.Section(), - section.Section(), - ], - next_page_token="abc", - ), - section.ListSectionsResponse( - sections=[], - next_page_token="def", - ), - section.ListSectionsResponse( - sections=[ - section.Section(), - ], - next_page_token="ghi", - ), - section.ListSectionsResponse( - sections=[ - section.Section(), - section.Section(), - ], - ), - RuntimeError, - ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_section.Section( + name="name_value", + display_name="display_name_value", + sort_order=1091, + type_=gc_section.Section.SectionType.CUSTOM_SECTION, ) - pager = client.list_sections(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout + response = client.update_section(request) - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gc_section.UpdateSectionRequest() + assert args[0] == request - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, section.Section) for i in results) + # Establish that the response is the type that we expect. + assert isinstance(response, gc_section.Section) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.sort_order == 1091 + assert response.type_ == gc_section.Section.SectionType.CUSTOM_SECTION -def test_list_sections_pages(transport_name: str = "grpc"): +def test_update_section_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport="grpc", ) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gc_section.UpdateSectionRequest() + # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_sections), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - section.ListSectionsResponse( - sections=[ - section.Section(), - section.Section(), - section.Section(), - ], - next_page_token="abc", - ), - section.ListSectionsResponse( - sections=[], - next_page_token="def", - ), - section.ListSectionsResponse( - sections=[ - section.Section(), - ], - next_page_token="ghi", - ), - section.ListSectionsResponse( - sections=[ - section.Section(), - section.Section(), - ], - ), - RuntimeError, - ) - pages = list(client.list_sections(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_sections_async_pager(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sections), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - section.ListSectionsResponse( - sections=[ - section.Section(), - section.Section(), - section.Section(), - ], - next_page_token="abc", - ), - section.ListSectionsResponse( - sections=[], - next_page_token="def", - ), - section.ListSectionsResponse( - sections=[ - section.Section(), - ], - next_page_token="ghi", - ), - section.ListSectionsResponse( - sections=[ - section.Section(), - section.Section(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_sections( - request={}, - ) - assert async_pager.next_page_token == "abc" - assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, section.Section) for i in responses) - - -@pytest.mark.asyncio -async def test_list_sections_async_pages(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sections), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - section.ListSectionsResponse( - sections=[ - section.Section(), - section.Section(), - section.Section(), - ], - next_page_token="abc", - ), - section.ListSectionsResponse( - sections=[], - next_page_token="def", - ), - section.ListSectionsResponse( - sections=[ - section.Section(), - ], - next_page_token="ghi", - ), - section.ListSectionsResponse( - sections=[ - section.Section(), - section.Section(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_sections(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", - [ - section.PositionSectionRequest(), - {}, - ], -) -def test_position_section(request_type, transport: str = "grpc"): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.position_section), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = section.PositionSectionResponse() - response = client.position_section(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = section.PositionSectionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, section.PositionSectionResponse) - - -def test_position_section_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = section.PositionSectionRequest( - name="name_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.position_section), "__call__") as call: + with mock.patch.object(type(client.transport.update_section), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.position_section(request=request) + client.update_section(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = section.PositionSectionRequest( - name="name_value", - ) + request_msg = gc_section.UpdateSectionRequest() assert args[0] == request_msg -def test_position_section_use_cached_wrapped_rpc(): +def test_update_section_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -17572,23 +17953,21 @@ def test_position_section_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.position_section in client._transport._wrapped_methods + assert client._transport.update_section in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.position_section] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.update_section] = mock_rpc request = {} - client.position_section(request) + client.update_section(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.position_section(request) + client.update_section(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -17596,7 +17975,7 @@ def test_position_section_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_position_section_async_use_cached_wrapped_rpc( +async def test_update_section_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -17613,7 +17992,7 @@ async def test_position_section_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.position_section + client._client._transport.update_section in client._client._transport._wrapped_methods ) @@ -17621,16 +18000,16 @@ async def test_position_section_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.position_section + client._client._transport.update_section ] = mock_rpc request = {} - await client.position_section(request) + await client.update_section(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.position_section(request) + await client.update_section(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -17641,11 +18020,11 @@ async def test_position_section_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - section.PositionSectionRequest(), + gc_section.UpdateSectionRequest(), {}, ], ) -async def test_position_section_async(request_type, transport: str = "grpc_asyncio"): +async def test_update_section_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -17656,38 +18035,47 @@ async def test_position_section_async(request_type, transport: str = "grpc_async request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.position_section), "__call__") as call: + with mock.patch.object(type(client.transport.update_section), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - section.PositionSectionResponse() + gc_section.Section( + name="name_value", + display_name="display_name_value", + sort_order=1091, + type_=gc_section.Section.SectionType.CUSTOM_SECTION, + ) ) - response = await client.position_section(request) + response = await client.update_section(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = section.PositionSectionRequest() + request = gc_section.UpdateSectionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, section.PositionSectionResponse) + assert isinstance(response, gc_section.Section) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.sort_order == 1091 + assert response.type_ == gc_section.Section.SectionType.CUSTOM_SECTION -def test_position_section_field_headers(): +def test_update_section_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = section.PositionSectionRequest() + request = gc_section.UpdateSectionRequest() - request.name = "name_value" + request.section.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.position_section), "__call__") as call: - call.return_value = section.PositionSectionResponse() - client.position_section(request) + with mock.patch.object(type(client.transport.update_section), "__call__") as call: + call.return_value = gc_section.Section() + client.update_section(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -17698,28 +18086,26 @@ def test_position_section_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "section.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_position_section_field_headers_async(): +async def test_update_section_field_headers_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = section.PositionSectionRequest() + request = gc_section.UpdateSectionRequest() - request.name = "name_value" + request.section.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.position_section), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - section.PositionSectionResponse() - ) - await client.position_section(request) + with mock.patch.object(type(client.transport.update_section), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_section.Section()) + await client.update_section(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -17730,18 +18116,108 @@ async def test_position_section_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "section.name=name_value", ) in kw["metadata"] +def test_update_section_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_section.Section() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_section( + section=gc_section.Section(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].section + mock_val = gc_section.Section(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_section_flattened_error(): + client = ChatServiceClient( + credentials=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_section( + gc_section.UpdateSectionRequest(), + section=gc_section.Section(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_section_flattened_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_section.Section() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_section.Section()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_section( + section=gc_section.Section(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].section + mock_val = gc_section.Section(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_section_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_section( + gc_section.UpdateSectionRequest(), + section=gc_section.Section(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + @pytest.mark.parametrize( "request_type", [ - section.ListSectionItemsRequest(), + section.ListSectionsRequest(), {}, ], ) -def test_list_section_items(request_type, transport: str = "grpc"): +def test_list_sections(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -17752,27 +18228,25 @@ def test_list_section_items(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_section_items), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_sections), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = section.ListSectionItemsResponse( + call.return_value = section.ListSectionsResponse( next_page_token="next_page_token_value", ) - response = client.list_section_items(request) + response = client.list_sections(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = section.ListSectionItemsRequest() + request = section.ListSectionsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSectionItemsPager) + assert isinstance(response, pagers.ListSectionsPager) assert response.next_page_token == "next_page_token_value" -def test_list_section_items_non_empty_request_with_auto_populated_field(): +def test_list_sections_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -17783,31 +18257,27 @@ def test_list_section_items_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = section.ListSectionItemsRequest( + request = section.ListSectionsRequest( parent="parent_value", page_token="page_token_value", - filter="filter_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_section_items), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_sections), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_section_items(request=request) + client.list_sections(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = section.ListSectionItemsRequest( + request_msg = section.ListSectionsRequest( parent="parent_value", page_token="page_token_value", - filter="filter_value", ) assert args[0] == request_msg -def test_list_section_items_use_cached_wrapped_rpc(): +def test_list_sections_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -17821,25 +18291,21 @@ def test_list_section_items_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_section_items in client._transport._wrapped_methods - ) + assert client._transport.list_sections in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_section_items] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.list_sections] = mock_rpc request = {} - client.list_section_items(request) + client.list_sections(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_section_items(request) + client.list_sections(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -17847,7 +18313,7 @@ def test_list_section_items_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_section_items_async_use_cached_wrapped_rpc( +async def test_list_sections_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -17864,7 +18330,7 @@ async def test_list_section_items_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_section_items + client._client._transport.list_sections in client._client._transport._wrapped_methods ) @@ -17872,16 +18338,16 @@ async def test_list_section_items_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_section_items + client._client._transport.list_sections ] = mock_rpc request = {} - await client.list_section_items(request) + await client.list_sections(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_section_items(request) + await client.list_sections(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -17892,11 +18358,11 @@ async def test_list_section_items_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - section.ListSectionItemsRequest(), + section.ListSectionsRequest(), {}, ], ) -async def test_list_section_items_async(request_type, transport: str = "grpc_asyncio"): +async def test_list_sections_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -17907,45 +18373,41 @@ async def test_list_section_items_async(request_type, transport: str = "grpc_asy request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_section_items), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_sections), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - section.ListSectionItemsResponse( + section.ListSectionsResponse( next_page_token="next_page_token_value", ) ) - response = await client.list_section_items(request) + response = await client.list_sections(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = section.ListSectionItemsRequest() + request = section.ListSectionsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSectionItemsAsyncPager) + assert isinstance(response, pagers.ListSectionsAsyncPager) assert response.next_page_token == "next_page_token_value" -def test_list_section_items_field_headers(): +def test_list_sections_field_headers(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = section.ListSectionItemsRequest() + request = section.ListSectionsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_section_items), "__call__" - ) as call: - call.return_value = section.ListSectionItemsResponse() - client.list_section_items(request) + with mock.patch.object(type(client.transport.list_sections), "__call__") as call: + call.return_value = section.ListSectionsResponse() + client.list_sections(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -17961,25 +18423,23 @@ def test_list_section_items_field_headers(): @pytest.mark.asyncio -async def test_list_section_items_field_headers_async(): +async def test_list_sections_field_headers_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = section.ListSectionItemsRequest() + request = section.ListSectionsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_section_items), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_sections), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - section.ListSectionItemsResponse() + section.ListSectionsResponse() ) - await client.list_section_items(request) + await client.list_sections(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -17994,20 +18454,18 @@ async def test_list_section_items_field_headers_async(): ) in kw["metadata"] -def test_list_section_items_flattened(): +def test_list_sections_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_section_items), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_sections), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = section.ListSectionItemsResponse() + call.return_value = section.ListSectionsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_section_items( + client.list_sections( parent="parent_value", ) @@ -18020,7 +18478,7 @@ def test_list_section_items_flattened(): assert arg == mock_val -def test_list_section_items_flattened_error(): +def test_list_sections_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -18028,31 +18486,29 @@ def test_list_section_items_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_section_items( - section.ListSectionItemsRequest(), + client.list_sections( + section.ListSectionsRequest(), parent="parent_value", ) @pytest.mark.asyncio -async def test_list_section_items_flattened_async(): +async def test_list_sections_flattened_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_section_items), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_sections), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = section.ListSectionItemsResponse() + call.return_value = section.ListSectionsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - section.ListSectionItemsResponse() + section.ListSectionsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_section_items( + response = await client.list_sections( parent="parent_value", ) @@ -18066,7 +18522,7 @@ async def test_list_section_items_flattened_async(): @pytest.mark.asyncio -async def test_list_section_items_flattened_error_async(): +async def test_list_sections_flattened_error_async(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -18074,46 +18530,44 @@ async def test_list_section_items_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_section_items( - section.ListSectionItemsRequest(), + await client.list_sections( + section.ListSectionsRequest(), parent="parent_value", ) -def test_list_section_items_pager(transport_name: str = "grpc"): +def test_list_sections_pager(transport_name: str = "grpc"): client = ChatServiceClient( 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_section_items), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_sections), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( - section.ListSectionItemsResponse( - section_items=[ - section.SectionItem(), - section.SectionItem(), - section.SectionItem(), + section.ListSectionsResponse( + sections=[ + section.Section(), + section.Section(), + section.Section(), ], next_page_token="abc", ), - section.ListSectionItemsResponse( - section_items=[], + section.ListSectionsResponse( + sections=[], next_page_token="def", ), - section.ListSectionItemsResponse( - section_items=[ - section.SectionItem(), + section.ListSectionsResponse( + sections=[ + section.Section(), ], next_page_token="ghi", ), - section.ListSectionItemsResponse( - section_items=[ - section.SectionItem(), - section.SectionItem(), + section.ListSectionsResponse( + sections=[ + section.Section(), + section.Section(), ], ), RuntimeError, @@ -18125,7 +18579,7 @@ def test_list_section_items_pager(transport_name: str = "grpc"): expected_metadata = tuple(expected_metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - pager = client.list_section_items(request={}, retry=retry, timeout=timeout) + pager = client.list_sections(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -18136,93 +18590,89 @@ def test_list_section_items_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, section.SectionItem) for i in results) + assert all(isinstance(i, section.Section) for i in results) -def test_list_section_items_pages(transport_name: str = "grpc"): +def test_list_sections_pages(transport_name: str = "grpc"): client = ChatServiceClient( 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_section_items), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_sections), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( - section.ListSectionItemsResponse( - section_items=[ - section.SectionItem(), - section.SectionItem(), - section.SectionItem(), + section.ListSectionsResponse( + sections=[ + section.Section(), + section.Section(), + section.Section(), ], next_page_token="abc", ), - section.ListSectionItemsResponse( - section_items=[], + section.ListSectionsResponse( + sections=[], next_page_token="def", ), - section.ListSectionItemsResponse( - section_items=[ - section.SectionItem(), + section.ListSectionsResponse( + sections=[ + section.Section(), ], next_page_token="ghi", ), - section.ListSectionItemsResponse( - section_items=[ - section.SectionItem(), - section.SectionItem(), + section.ListSectionsResponse( + sections=[ + section.Section(), + section.Section(), ], ), RuntimeError, ) - pages = list(client.list_section_items(request={}).pages) + pages = list(client.list_sections(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_section_items_async_pager(): +async def test_list_sections_async_pager(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_section_items), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_sections), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( - section.ListSectionItemsResponse( - section_items=[ - section.SectionItem(), - section.SectionItem(), - section.SectionItem(), + section.ListSectionsResponse( + sections=[ + section.Section(), + section.Section(), + section.Section(), ], next_page_token="abc", ), - section.ListSectionItemsResponse( - section_items=[], + section.ListSectionsResponse( + sections=[], next_page_token="def", ), - section.ListSectionItemsResponse( - section_items=[ - section.SectionItem(), + section.ListSectionsResponse( + sections=[ + section.Section(), ], next_page_token="ghi", ), - section.ListSectionItemsResponse( - section_items=[ - section.SectionItem(), - section.SectionItem(), + section.ListSectionsResponse( + sections=[ + section.Section(), + section.Section(), ], ), RuntimeError, ) - async_pager = await client.list_section_items( + async_pager = await client.list_sections( request={}, ) assert async_pager.next_page_token == "abc" @@ -18233,51 +18683,49 @@ async def test_list_section_items_async_pager(): responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, section.SectionItem) for i in responses) + assert all(isinstance(i, section.Section) for i in responses) @pytest.mark.asyncio -async def test_list_section_items_async_pages(): +async def test_list_sections_async_pages(): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_section_items), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_sections), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( - section.ListSectionItemsResponse( - section_items=[ - section.SectionItem(), - section.SectionItem(), - section.SectionItem(), + section.ListSectionsResponse( + sections=[ + section.Section(), + section.Section(), + section.Section(), ], next_page_token="abc", ), - section.ListSectionItemsResponse( - section_items=[], + section.ListSectionsResponse( + sections=[], next_page_token="def", ), - section.ListSectionItemsResponse( - section_items=[ - section.SectionItem(), + section.ListSectionsResponse( + sections=[ + section.Section(), ], next_page_token="ghi", ), - section.ListSectionItemsResponse( - section_items=[ - section.SectionItem(), - section.SectionItem(), + section.ListSectionsResponse( + sections=[ + section.Section(), + section.Section(), ], ), RuntimeError, ) pages = [] - async for page_ in (await client.list_section_items(request={})).pages: + async for page_ in (await client.list_sections(request={})).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -18286,11 +18734,249 @@ async def test_list_section_items_async_pages(): @pytest.mark.parametrize( "request_type", [ - section.MoveSectionItemRequest(), + section.PositionSectionRequest(), {}, ], ) -def test_move_section_item(request_type, transport: str = "grpc"): +def test_position_section(request_type, transport: str = "grpc"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.position_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = section.PositionSectionResponse() + response = client.position_section(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = section.PositionSectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, section.PositionSectionResponse) + + +def test_position_section_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = section.PositionSectionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.position_section), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.position_section(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = section.PositionSectionRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_position_section_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.position_section in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.position_section] = ( + mock_rpc + ) + request = {} + client.position_section(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.position_section(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_position_section_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.position_section + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.position_section + ] = mock_rpc + + request = {} + await client.position_section(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.position_section(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + section.PositionSectionRequest(), + {}, + ], +) +async def test_position_section_async(request_type, transport: str = "grpc_asyncio"): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.position_section), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.PositionSectionResponse() + ) + response = await client.position_section(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = section.PositionSectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, section.PositionSectionResponse) + + +def test_position_section_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = section.PositionSectionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.position_section), "__call__") as call: + call.return_value = section.PositionSectionResponse() + client.position_section(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_position_section_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = section.PositionSectionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.position_section), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.PositionSectionResponse() + ) + await client.position_section(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + section.ListSectionItemsRequest(), + {}, + ], +) +def test_list_section_items(request_type, transport: str = "grpc"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18302,23 +18988,26 @@ def test_move_section_item(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.move_section_item), "__call__" + type(client.transport.list_section_items), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = section.MoveSectionItemResponse() - response = client.move_section_item(request) + call.return_value = section.ListSectionItemsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_section_items(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = section.MoveSectionItemRequest() + request = section.ListSectionItemsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, section.MoveSectionItemResponse) + assert isinstance(response, pagers.ListSectionItemsPager) + assert response.next_page_token == "next_page_token_value" -def test_move_section_item_non_empty_request_with_auto_populated_field(): +def test_list_section_items_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = ChatServiceClient( @@ -18329,29 +19018,31 @@ def test_move_section_item_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = section.MoveSectionItemRequest( - name="name_value", - target_section="target_section_value", + request = section.ListSectionItemsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.move_section_item), "__call__" + type(client.transport.list_section_items), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.move_section_item(request=request) + client.list_section_items(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = section.MoveSectionItemRequest( - name="name_value", - target_section="target_section_value", + request_msg = section.ListSectionItemsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", ) assert args[0] == request_msg -def test_move_section_item_use_cached_wrapped_rpc(): +def test_list_section_items_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -18365,23 +19056,25 @@ def test_move_section_item_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.move_section_item in client._transport._wrapped_methods + assert ( + client._transport.list_section_items in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.move_section_item] = ( + client._transport._wrapped_methods[client._transport.list_section_items] = ( mock_rpc ) request = {} - client.move_section_item(request) + client.list_section_items(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.move_section_item(request) + client.list_section_items(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -18389,7 +19082,7 @@ def test_move_section_item_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_move_section_item_async_use_cached_wrapped_rpc( +async def test_list_section_items_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -18406,7 +19099,7 @@ async def test_move_section_item_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.move_section_item + client._client._transport.list_section_items in client._client._transport._wrapped_methods ) @@ -18414,16 +19107,16 @@ async def test_move_section_item_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.move_section_item + client._client._transport.list_section_items ] = mock_rpc request = {} - await client.move_section_item(request) + await client.list_section_items(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.move_section_item(request) + await client.list_section_items(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -18434,11 +19127,11 @@ async def test_move_section_item_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - section.MoveSectionItemRequest(), + section.ListSectionItemsRequest(), {}, ], ) -async def test_move_section_item_async(request_type, transport: str = "grpc_asyncio"): +async def test_list_section_items_async(request_type, transport: str = "grpc_asyncio"): client = ChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -18450,186 +19143,1399 @@ async def test_move_section_item_async(request_type, transport: str = "grpc_asyn # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.move_section_item), "__call__" + type(client.transport.list_section_items), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - section.MoveSectionItemResponse() + section.ListSectionItemsResponse( + next_page_token="next_page_token_value", + ) ) - response = await client.move_section_item(request) + response = await client.list_section_items(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = section.MoveSectionItemRequest() + request = section.ListSectionItemsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, section.MoveSectionItemResponse) + assert isinstance(response, pagers.ListSectionItemsAsyncPager) + assert response.next_page_token == "next_page_token_value" -def test_move_section_item_field_headers(): +def test_list_section_items_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = section.ListSectionItemsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_section_items), "__call__" + ) as call: + call.return_value = section.ListSectionItemsResponse() + client.list_section_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_section_items_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = section.ListSectionItemsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_section_items), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.ListSectionItemsResponse() + ) + await client.list_section_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_section_items_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_section_items), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = section.ListSectionItemsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_section_items( + 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_section_items_flattened_error(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = section.MoveSectionItemRequest() + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_section_items( + section.ListSectionItemsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_section_items_flattened_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_section_items), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = section.ListSectionItemsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.ListSectionItemsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_section_items( + 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_section_items_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_section_items( + section.ListSectionItemsRequest(), + parent="parent_value", + ) + + +def test_list_section_items_pager(transport_name: str = "grpc"): + client = ChatServiceClient( + 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_section_items), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + section.SectionItem(), + section.SectionItem(), + ], + next_page_token="abc", + ), + section.ListSectionItemsResponse( + section_items=[], + next_page_token="def", + ), + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + ], + next_page_token="ghi", + ), + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + section.SectionItem(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_section_items(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, section.SectionItem) for i in results) + + +def test_list_section_items_pages(transport_name: str = "grpc"): + client = ChatServiceClient( + 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_section_items), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + section.SectionItem(), + section.SectionItem(), + ], + next_page_token="abc", + ), + section.ListSectionItemsResponse( + section_items=[], + next_page_token="def", + ), + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + ], + next_page_token="ghi", + ), + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + section.SectionItem(), + ], + ), + RuntimeError, + ) + pages = list(client.list_section_items(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_section_items_async_pager(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_section_items), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + section.SectionItem(), + section.SectionItem(), + ], + next_page_token="abc", + ), + section.ListSectionItemsResponse( + section_items=[], + next_page_token="def", + ), + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + ], + next_page_token="ghi", + ), + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + section.SectionItem(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_section_items( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, section.SectionItem) for i in responses) + + +@pytest.mark.asyncio +async def test_list_section_items_async_pages(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_section_items), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + section.SectionItem(), + section.SectionItem(), + ], + next_page_token="abc", + ), + section.ListSectionItemsResponse( + section_items=[], + next_page_token="def", + ), + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + ], + next_page_token="ghi", + ), + section.ListSectionItemsResponse( + section_items=[ + section.SectionItem(), + section.SectionItem(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_section_items(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", + [ + section.MoveSectionItemRequest(), + {}, + ], +) +def test_move_section_item(request_type, transport: str = "grpc"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_section_item), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = section.MoveSectionItemResponse() + response = client.move_section_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = section.MoveSectionItemRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, section.MoveSectionItemResponse) + + +def test_move_section_item_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = section.MoveSectionItemRequest( + name="name_value", + target_section="target_section_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_section_item), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.move_section_item(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = section.MoveSectionItemRequest( + name="name_value", + target_section="target_section_value", + ) + assert args[0] == request_msg + + +def test_move_section_item_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.move_section_item in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.move_section_item] = ( + mock_rpc + ) + request = {} + client.move_section_item(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.move_section_item(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_move_section_item_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.move_section_item + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.move_section_item + ] = mock_rpc + + request = {} + await client.move_section_item(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.move_section_item(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + section.MoveSectionItemRequest(), + {}, + ], +) +async def test_move_section_item_async(request_type, transport: str = "grpc_asyncio"): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_section_item), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.MoveSectionItemResponse() + ) + response = await client.move_section_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = section.MoveSectionItemRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, section.MoveSectionItemResponse) + + +def test_move_section_item_field_headers(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = section.MoveSectionItemRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_section_item), "__call__" + ) as call: + call.return_value = section.MoveSectionItemResponse() + client.move_section_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_move_section_item_field_headers_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = section.MoveSectionItemRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_section_item), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.MoveSectionItemResponse() + ) + await client.move_section_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_move_section_item_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_section_item), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = section.MoveSectionItemResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.move_section_item( + name="name_value", + target_section="target_section_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].target_section + mock_val = "target_section_value" + assert arg == mock_val + + +def test_move_section_item_flattened_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.move_section_item( + section.MoveSectionItemRequest(), + name="name_value", + target_section="target_section_value", + ) + + +@pytest.mark.asyncio +async def test_move_section_item_flattened_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.move_section_item), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = section.MoveSectionItemResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + section.MoveSectionItemResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.move_section_item( + name="name_value", + target_section="target_section_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].target_section + mock_val = "target_section_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_move_section_item_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.move_section_item( + section.MoveSectionItemRequest(), + name="name_value", + target_section="target_section_value", + ) + + +def test_create_message_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_message in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_message] = mock_rpc + + request = {} + client.create_message(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_message(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_message_rest_required_fields( + request_type=gc_message.CreateMessageRequest, +): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseCreateMessage, + "_BaseCreateMessage__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "createMessageNotificationOptions", + "messageId", + "messageReplyOption", + "requestId", + "threadKey", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gc_message.Message() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gc_message.Message.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_message(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_message_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gc_message.Message() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "spaces/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + message=gc_message.Message(name="name_value"), + message_id="message_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_message.Message.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_message(**mock_args) + + # Establish that the underlying call 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=spaces/*}/messages" % client.transport._host, args[1] + ) + + +def test_create_message_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.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_message( + gc_message.CreateMessageRequest(), + parent="parent_value", + message=gc_message.Message(name="name_value"), + message_id="message_id_value", + ) + + +def test_list_messages_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_messages in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_messages] = mock_rpc + + request = {} + client.list_messages(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_messages(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_messages_rest_required_fields(request_type=message.ListMessagesRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListMessages, + "_BaseListMessages__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "markupSyntax", + "orderBy", + "pageSize", + "pageToken", + "showDeleted", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = message.ListMessagesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = message.ListMessagesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_messages(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_messages_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = message.ListMessagesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "spaces/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = message.ListMessagesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_messages(**mock_args) + + # Establish that the underlying call 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=spaces/*}/messages" % client.transport._host, args[1] + ) + + +def test_list_messages_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.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_messages( + message.ListMessagesRequest(), + parent="parent_value", + ) + + +def test_list_messages_rest_pager(transport: str = "rest"): + client = ChatServiceClient( + 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 = ( + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + message.Message(), + ], + next_page_token="abc", + ), + message.ListMessagesResponse( + messages=[], + next_page_token="def", + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + ], + next_page_token="ghi", + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(message.ListMessagesResponse.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": "spaces/sample1"} + + pager = client.list_messages(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, message.Message) for i in results) + + pages = list(client.list_messages(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_memberships_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_memberships in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_memberships] = ( + mock_rpc + ) + + request = {} + client.list_memberships(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_memberships(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_memberships_rest_required_fields( + request_type=membership.ListMembershipsRequest, +): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped - request.name = "name_value" + default_values = getattr( + transport_class._BaseListMemberships, + "_BaseListMemberships__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.move_section_item), "__call__" - ) as call: - call.return_value = section.MoveSectionItemResponse() - client.move_section_item(request) + # verify required fields with default values are now present - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request + jsonified_request["parent"] = "parent_value" - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "pageSize", + "pageToken", + "showGroups", + "showInvited", + "useAdminAccess", + ) + ) + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" -@pytest.mark.asyncio -async def test_move_section_item_field_headers_async(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = request_type(**request_init) - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = section.MoveSectionItemRequest() + # Designate an appropriate value for the returned response. + return_value = membership.ListMembershipsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 - request.name = "name_value" + response_value = Response() + response_value.status_code = 200 - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.move_section_item), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - section.MoveSectionItemResponse() - ) - await client.move_section_item(request) + # Convert return value to protobuf type + return_value = membership.ListMembershipsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + response = client.list_memberships(request) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -def test_move_section_item_flattened(): + +def test_list_memberships_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.move_section_item), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = section.MoveSectionItemResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.move_section_item( - name="name_value", - target_section="target_section_value", + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = membership.ListMembershipsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "spaces/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = membership.ListMembershipsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_memberships(**mock_args) # Establish that the underlying call was made with the expected # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - arg = args[0].target_section - mock_val = "target_section_value" - assert arg == mock_val + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=spaces/*}/members" % client.transport._host, args[1] + ) -def test_move_section_item_flattened_error(): +def test_list_memberships_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.move_section_item( - section.MoveSectionItemRequest(), - name="name_value", - target_section="target_section_value", + client.list_memberships( + membership.ListMembershipsRequest(), + parent="parent_value", ) -@pytest.mark.asyncio -async def test_move_section_item_flattened_async(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), +def test_list_memberships_rest_pager(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.move_section_item), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = section.MoveSectionItemResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - section.MoveSectionItemResponse() + # 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 = ( + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token="abc", + ), + membership.ListMembershipsResponse( + memberships=[], + next_page_token="def", + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + ], + next_page_token="ghi", + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + ], + ), ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.move_section_item( - name="name_value", - target_section="target_section_value", + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + membership.ListMembershipsResponse.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 - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - arg = args[0].target_section - mock_val = "target_section_value" - assert arg == mock_val + sample_request = {"parent": "spaces/sample1"} + pager = client.list_memberships(request=sample_request) -@pytest.mark.asyncio -async def test_move_section_item_flattened_error_async(): - client = ChatServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.move_section_item( - section.MoveSectionItemRequest(), - name="name_value", - target_section="target_section_value", - ) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, membership.Membership) for i in results) + + pages = list(client.list_memberships(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_create_message_rest_use_cached_wrapped_rpc(): +def test_get_membership_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -18643,35 +20549,35 @@ def test_create_message_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_message in client._transport._wrapped_methods + assert client._transport.get_membership in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_message] = mock_rpc + client._transport._wrapped_methods[client._transport.get_membership] = mock_rpc request = {} - client.create_message(request) + client.get_membership(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_message(request) + client.get_membership(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_message_rest_required_fields( - request_type=gc_message.CreateMessageRequest, +def test_get_membership_rest_required_fields( + request_type=membership.GetMembershipRequest, ): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -18681,8 +20587,8 @@ def test_create_message_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseCreateMessage, - "_BaseCreateMessage__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetMembership, + "_BaseGetMembership__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -18692,22 +20598,14 @@ def test_create_message_rest_required_fields( # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "createMessageNotificationOptions", - "messageId", - "messageReplyOption", - "requestId", - "threadKey", - ) - ) + assert not set(unset_fields) - set(("useAdminAccess",)) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -18716,7 +20614,7 @@ def test_create_message_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gc_message.Message() + return_value = membership.Membership() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -18728,31 +20626,30 @@ def test_create_message_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_message.Message.pb(return_value) + return_value = membership.Membership.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_message(request) + response = client.get_membership(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_message_rest_flattened(): +def test_get_membership_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -18761,16 +20658,14 @@ def test_create_message_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gc_message.Message() + return_value = membership.Membership() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "spaces/sample1"} + sample_request = {"name": "spaces/sample1/members/sample2"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - message=gc_message.Message(name="name_value"), - message_id="message_id_value", + name="name_value", ) mock_args.update(sample_request) @@ -18778,24 +20673,24 @@ def test_create_message_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_message.Message.pb(return_value) + return_value = membership.Membership.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_message(**mock_args) + client.get_membership(**mock_args) # Establish that the underlying call 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=spaces/*}/messages" % client.transport._host, args[1] + "%s/v1/{name=spaces/*/members/*}" % client.transport._host, args[1] ) -def test_create_message_rest_flattened_error(transport: str = "rest"): +def test_get_membership_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18804,15 +20699,13 @@ def test_create_message_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_message( - gc_message.CreateMessageRequest(), - parent="parent_value", - message=gc_message.Message(name="name_value"), - message_id="message_id_value", + client.get_membership( + membership.GetMembershipRequest(), + name="name_value", ) -def test_list_messages_rest_use_cached_wrapped_rpc(): +def test_get_message_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -18826,33 +20719,33 @@ def test_list_messages_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_messages in client._transport._wrapped_methods + assert client._transport.get_message in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_messages] = mock_rpc + client._transport._wrapped_methods[client._transport.get_message] = mock_rpc request = {} - client.list_messages(request) + client.get_message(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_messages(request) + client.get_message(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_messages_rest_required_fields(request_type=message.ListMessagesRequest): +def test_get_message_rest_required_fields(request_type=message.GetMessageRequest): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -18862,8 +20755,8 @@ def test_list_messages_rest_required_fields(request_type=message.ListMessagesReq # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListMessages, - "_BaseListMessages__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetMessage, + "_BaseGetMessage__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -18873,23 +20766,14 @@ def test_list_messages_rest_required_fields(request_type=message.ListMessagesReq # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "markupSyntax", - "orderBy", - "pageSize", - "pageToken", - "showDeleted", - ) - ) + assert not set(unset_fields) - set(("markupSyntax",)) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -18898,7 +20782,7 @@ def test_list_messages_rest_required_fields(request_type=message.ListMessagesReq request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = message.ListMessagesResponse() + return_value = message.Message() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -18919,21 +20803,21 @@ def test_list_messages_rest_required_fields(request_type=message.ListMessagesReq response_value.status_code = 200 # Convert return value to protobuf type - return_value = message.ListMessagesResponse.pb(return_value) + return_value = message.Message.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_messages(request) + response = client.get_message(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_messages_rest_flattened(): +def test_get_message_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -18942,14 +20826,14 @@ def test_list_messages_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = message.ListMessagesResponse() + return_value = message.Message() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "spaces/sample1"} + sample_request = {"name": "spaces/sample1/messages/sample2"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) @@ -18957,24 +20841,24 @@ def test_list_messages_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = message.ListMessagesResponse.pb(return_value) + return_value = message.Message.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_messages(**mock_args) + client.get_message(**mock_args) # Establish that the underlying call 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=spaces/*}/messages" % client.transport._host, args[1] + "%s/v1/{name=spaces/*/messages/*}" % client.transport._host, args[1] ) -def test_list_messages_rest_flattened_error(transport: str = "rest"): +def test_get_message_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18983,77 +20867,13 @@ def test_list_messages_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_messages( - message.ListMessagesRequest(), - parent="parent_value", - ) - - -def test_list_messages_rest_pager(transport: str = "rest"): - client = ChatServiceClient( - 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 = ( - message.ListMessagesResponse( - messages=[ - message.Message(), - message.Message(), - message.Message(), - ], - next_page_token="abc", - ), - message.ListMessagesResponse( - messages=[], - next_page_token="def", - ), - message.ListMessagesResponse( - messages=[ - message.Message(), - ], - next_page_token="ghi", - ), - message.ListMessagesResponse( - messages=[ - message.Message(), - message.Message(), - ], - ), + client.get_message( + message.GetMessageRequest(), + name="name_value", ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(message.ListMessagesResponse.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": "spaces/sample1"} - - pager = client.list_messages(request=sample_request) - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, message.Message) for i in results) - - pages = list(client.list_messages(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token -def test_list_memberships_rest_use_cached_wrapped_rpc(): +def test_update_message_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -19067,37 +20887,34 @@ def test_list_memberships_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_memberships in client._transport._wrapped_methods + assert client._transport.update_message in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_memberships] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.update_message] = mock_rpc request = {} - client.list_memberships(request) + client.update_message(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_memberships(request) + client.update_message(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_memberships_rest_required_fields( - request_type=membership.ListMembershipsRequest, +def test_update_message_rest_required_fields( + request_type=gc_message.UpdateMessageRequest, ): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -19107,8 +20924,8 @@ def test_list_memberships_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListMemberships, - "_BaseListMemberships__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseUpdateMessage, + "_BaseUpdateMessage__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -19118,23 +20935,15 @@ def test_list_memberships_rest_required_fields( # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "filter", - "pageSize", - "pageToken", - "showGroups", - "showInvited", - "useAdminAccess", + "allowMissing", + "updateMask", ) ) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -19143,7 +20952,7 @@ def test_list_memberships_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = membership.ListMembershipsResponse() + return_value = gc_message.Message() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -19155,30 +20964,31 @@ def test_list_memberships_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "put", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = membership.ListMembershipsResponse.pb(return_value) + return_value = gc_message.Message.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_memberships(request) + response = client.update_message(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_memberships_rest_flattened(): +def test_update_message_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -19187,14 +20997,15 @@ def test_list_memberships_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = membership.ListMembershipsResponse() + return_value = gc_message.Message() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "spaces/sample1"} + sample_request = {"message": {"name": "spaces/sample1/messages/sample2"}} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + message=gc_message.Message(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -19202,24 +21013,24 @@ def test_list_memberships_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = membership.ListMembershipsResponse.pb(return_value) + return_value = gc_message.Message.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_memberships(**mock_args) + client.update_message(**mock_args) # Establish that the underlying call 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=spaces/*}/members" % client.transport._host, args[1] + "%s/v1/{message.name=spaces/*/messages/*}" % client.transport._host, args[1] ) -def test_list_memberships_rest_flattened_error(transport: str = "rest"): +def test_update_message_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -19228,79 +21039,14 @@ def test_list_memberships_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_memberships( - membership.ListMembershipsRequest(), - parent="parent_value", - ) - - -def test_list_memberships_rest_pager(transport: str = "rest"): - client = ChatServiceClient( - 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 = ( - membership.ListMembershipsResponse( - memberships=[ - membership.Membership(), - membership.Membership(), - membership.Membership(), - ], - next_page_token="abc", - ), - membership.ListMembershipsResponse( - memberships=[], - next_page_token="def", - ), - membership.ListMembershipsResponse( - memberships=[ - membership.Membership(), - ], - next_page_token="ghi", - ), - membership.ListMembershipsResponse( - memberships=[ - membership.Membership(), - membership.Membership(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - membership.ListMembershipsResponse.to_json(x) for x in response + client.update_message( + gc_message.UpdateMessageRequest(), + message=gc_message.Message(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - 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": "spaces/sample1"} - - pager = client.list_memberships(request=sample_request) - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, membership.Membership) for i in results) - - pages = list(client.list_memberships(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token -def test_get_membership_rest_use_cached_wrapped_rpc(): +def test_delete_message_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -19314,31 +21060,29 @@ def test_get_membership_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_membership in client._transport._wrapped_methods + assert client._transport.delete_message in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_membership] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_message] = mock_rpc request = {} - client.get_membership(request) + client.delete_message(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_membership(request) + client.delete_message(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_membership_rest_required_fields( - request_type=membership.GetMembershipRequest, -): +def test_delete_message_rest_required_fields(request_type=message.DeleteMessageRequest): transport_class = transports.ChatServiceRestTransport request_init = {} @@ -19352,8 +21096,8 @@ def test_get_membership_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetMembership, - "_BaseGetMembership__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseDeleteMessage, + "_BaseDeleteMessage__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -19366,7 +21110,7 @@ def test_get_membership_rest_required_fields( jsonified_request["name"] = "name_value" # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("useAdminAccess",)) + assert not set(unset_fields) - set(("force",)) # verify required fields with non-default values are left alone assert "name" in jsonified_request @@ -19379,7 +21123,7 @@ def test_get_membership_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = membership.Membership() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -19391,30 +21135,27 @@ def test_get_membership_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "delete", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = membership.Membership.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_membership(request) + response = client.delete_message(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_membership_rest_flattened(): +def test_delete_message_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -19423,10 +21164,10 @@ def test_get_membership_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = membership.Membership() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1/members/sample2"} + sample_request = {"name": "spaces/sample1/messages/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -19437,25 +21178,23 @@ def test_get_membership_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = membership.Membership.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_membership(**mock_args) + client.delete_message(**mock_args) # Establish that the underlying call 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=spaces/*/members/*}" % client.transport._host, args[1] + "%s/v1/{name=spaces/*/messages/*}" % client.transport._host, args[1] ) -def test_get_membership_rest_flattened_error(transport: str = "rest"): +def test_delete_message_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -19464,13 +21203,13 @@ def test_get_membership_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_membership( - membership.GetMembershipRequest(), + client.delete_message( + message.DeleteMessageRequest(), name="name_value", ) -def test_get_message_rest_use_cached_wrapped_rpc(): +def test_search_messages_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -19484,33 +21223,36 @@ def test_get_message_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_message in client._transport._wrapped_methods + assert client._transport.search_messages in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_message] = mock_rpc + client._transport._wrapped_methods[client._transport.search_messages] = mock_rpc request = {} - client.get_message(request) + client.search_messages(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_message(request) + client.search_messages(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_message_rest_required_fields(request_type=message.GetMessageRequest): +def test_search_messages_rest_required_fields( + request_type=message.SearchMessagesRequest, +): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["filter"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -19520,8 +21262,8 @@ def test_get_message_rest_required_fields(request_type=message.GetMessageRequest # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetMessage, - "_BaseGetMessage__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseSearchMessages, + "_BaseSearchMessages__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -19531,14 +21273,14 @@ def test_get_message_rest_required_fields(request_type=message.GetMessageRequest # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("markupSyntax",)) + jsonified_request["parent"] = "parent_value" + jsonified_request["filter"] = "filter_value" # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "filter" in jsonified_request + assert jsonified_request["filter"] == "filter_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -19547,7 +21289,7 @@ def test_get_message_rest_required_fields(request_type=message.GetMessageRequest request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = message.Message() + return_value = message.SearchMessagesResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -19559,30 +21301,31 @@ def test_get_message_rest_required_fields(request_type=message.GetMessageRequest pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = message.Message.pb(return_value) + return_value = message.SearchMessagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_message(request) + response = client.search_messages(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_message_rest_flattened(): +def test_search_messages_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -19591,14 +21334,15 @@ def test_get_message_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = message.Message() + return_value = message.SearchMessagesResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1/messages/sample2"} + sample_request = {"parent": "spaces/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + filter="filter_value", ) mock_args.update(sample_request) @@ -19606,24 +21350,24 @@ def test_get_message_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = message.Message.pb(return_value) + return_value = message.SearchMessagesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_message(**mock_args) + client.search_messages(**mock_args) # Establish that the underlying call 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=spaces/*/messages/*}" % client.transport._host, args[1] + "%s/v1/{parent=spaces/*}/messages:search" % client.transport._host, args[1] ) -def test_get_message_rest_flattened_error(transport: str = "rest"): +def test_search_messages_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -19632,13 +21376,78 @@ def test_get_message_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_message( - message.GetMessageRequest(), - name="name_value", + client.search_messages( + message.SearchMessagesRequest(), + parent="parent_value", + filter="filter_value", ) -def test_update_message_rest_use_cached_wrapped_rpc(): +def test_search_messages_rest_pager(transport: str = "rest"): + client = ChatServiceClient( + 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 = ( + message.SearchMessagesResponse( + results=[ + message.SearchMessageResult(), + message.SearchMessageResult(), + message.SearchMessageResult(), + ], + next_page_token="abc", + ), + message.SearchMessagesResponse( + results=[], + next_page_token="def", + ), + message.SearchMessagesResponse( + results=[ + message.SearchMessageResult(), + ], + next_page_token="ghi", + ), + message.SearchMessagesResponse( + results=[ + message.SearchMessageResult(), + message.SearchMessageResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(message.SearchMessagesResponse.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": "spaces/sample1"} + + pager = client.search_messages(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, message.SearchMessageResult) for i in results) + + pages = list(client.search_messages(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_attachment_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -19652,34 +21461,35 @@ def test_update_message_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_message in client._transport._wrapped_methods + assert client._transport.get_attachment in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_message] = mock_rpc + client._transport._wrapped_methods[client._transport.get_attachment] = mock_rpc request = {} - client.update_message(request) + client.get_attachment(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_message(request) + client.get_attachment(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_message_rest_required_fields( - request_type=gc_message.UpdateMessageRequest, +def test_get_attachment_rest_required_fields( + request_type=attachment.GetAttachmentRequest, ): transport_class = transports.ChatServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -19689,8 +21499,8 @@ def test_update_message_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseUpdateMessage, - "_BaseUpdateMessage__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetAttachment, + "_BaseGetAttachment__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -19700,15 +21510,11 @@ def test_update_message_rest_required_fields( # verify required fields with default values are now present - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "allowMissing", - "updateMask", - ) - ) + jsonified_request["name"] = "name_value" # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -19717,7 +21523,7 @@ def test_update_message_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gc_message.Message() + return_value = attachment.Attachment() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -19729,31 +21535,30 @@ def test_update_message_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "put", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_message.Message.pb(return_value) + return_value = attachment.Attachment.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_message(request) + response = client.get_attachment(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_message_rest_flattened(): +def test_get_attachment_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -19762,15 +21567,14 @@ def test_update_message_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gc_message.Message() + return_value = attachment.Attachment() # get arguments that satisfy an http rule for this method - sample_request = {"message": {"name": "spaces/sample1/messages/sample2"}} + sample_request = {"name": "spaces/sample1/messages/sample2/attachments/sample3"} # get truthy value for each flattened field mock_args = dict( - message=gc_message.Message(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -19778,24 +21582,25 @@ def test_update_message_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_message.Message.pb(return_value) + return_value = attachment.Attachment.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_message(**mock_args) + client.get_attachment(**mock_args) # Establish that the underlying call 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/{message.name=spaces/*/messages/*}" % client.transport._host, args[1] + "%s/v1/{name=spaces/*/messages/*/attachments/*}" % client.transport._host, + args[1], ) -def test_update_message_rest_flattened_error(transport: str = "rest"): +def test_get_attachment_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -19804,14 +21609,13 @@ def test_update_message_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_message( - gc_message.UpdateMessageRequest(), - message=gc_message.Message(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_attachment( + attachment.GetAttachmentRequest(), + name="name_value", ) -def test_delete_message_rest_use_cached_wrapped_rpc(): +def test_upload_attachment_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -19825,33 +21629,38 @@ def test_delete_message_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_message in client._transport._wrapped_methods + assert client._transport.upload_attachment in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_message] = mock_rpc + client._transport._wrapped_methods[client._transport.upload_attachment] = ( + mock_rpc + ) request = {} - client.delete_message(request) + client.upload_attachment(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_message(request) + client.upload_attachment(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_message_rest_required_fields(request_type=message.DeleteMessageRequest): +def test_upload_attachment_rest_required_fields( + request_type=attachment.UploadAttachmentRequest, +): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["filename"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -19861,8 +21670,8 @@ def test_delete_message_rest_required_fields(request_type=message.DeleteMessageR # verify fields with default values are dropped default_values = getattr( - transport_class._BaseDeleteMessage, - "_BaseDeleteMessage__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseUploadAttachment, + "_BaseUploadAttachment__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -19872,14 +21681,14 @@ def test_delete_message_rest_required_fields(request_type=message.DeleteMessageR # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("force",)) + jsonified_request["parent"] = "parent_value" + jsonified_request["filename"] = "filename_value" # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "filename" in jsonified_request + assert jsonified_request["filename"] == "filename_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -19888,7 +21697,7 @@ def test_delete_message_rest_required_fields(request_type=message.DeleteMessageR request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = attachment.UploadAttachmentResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -19900,81 +21709,131 @@ def test_delete_message_rest_required_fields(request_type=message.DeleteMessageR pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "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 = "" + + # Convert return value to protobuf type + return_value = attachment.UploadAttachmentResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_message(request) + response = client.upload_attachment(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_message_rest_flattened(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_list_spaces_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Mock the http request call within the method and 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 + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1/messages/sample2"} + # Ensure method has been cached + assert client._transport.list_spaces in client._transport._wrapped_methods - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - mock_args.update(sample_request) + client._transport._wrapped_methods[client._transport.list_spaces] = mock_rpc - # 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + request = {} + client.list_spaces(request) - client.delete_message(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Establish that the underlying call 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=spaces/*/messages/*}" % client.transport._host, args[1] - ) + client.list_spaces(request) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -def test_delete_message_rest_flattened_error(transport: str = "rest"): + +def test_list_spaces_rest_pager(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.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_message( - message.DeleteMessageRequest(), - name="name_value", + # 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 = ( + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + space.Space(), + ], + next_page_token="abc", + ), + space.ListSpacesResponse( + spaces=[], + next_page_token="def", + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + ], + next_page_token="ghi", + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + ], + ), ) + # Two responses for two calls + response = response + response + # Wrap the values into proper Response objs + response = tuple(space.ListSpacesResponse.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 -def test_search_messages_rest_use_cached_wrapped_rpc(): + sample_request = {} + + pager = client.list_spaces(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, space.Space) for i in results) + + pages = list(client.list_spaces(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_search_spaces_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -19988,36 +21847,33 @@ def test_search_messages_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.search_messages in client._transport._wrapped_methods + assert client._transport.search_spaces in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.search_messages] = mock_rpc + client._transport._wrapped_methods[client._transport.search_spaces] = mock_rpc request = {} - client.search_messages(request) + client.search_spaces(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.search_messages(request) + client.search_spaces(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_search_messages_rest_required_fields( - request_type=message.SearchMessagesRequest, -): +def test_search_spaces_rest_required_fields(request_type=space.SearchSpacesRequest): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["parent"] = "" - request_init["filter"] = "" + request_init["query"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -20025,10 +21881,11 @@ def test_search_messages_rest_required_fields( ) # verify fields with default values are dropped + assert "query" not in jsonified_request default_values = getattr( - transport_class._BaseSearchMessages, - "_BaseSearchMessages__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseSearchSpaces, + "_BaseSearchSpaces__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -20037,15 +21894,25 @@ def test_search_messages_rest_required_fields( jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "query" in jsonified_request + assert jsonified_request["query"] == request_init["query"] - jsonified_request["parent"] = "parent_value" - jsonified_request["filter"] = "filter_value" + jsonified_request["query"] = "query_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "orderBy", + "pageSize", + "pageToken", + "query", + "useAdminAccess", + ) + ) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "filter" in jsonified_request - assert jsonified_request["filter"] == "filter_value" + assert "query" in jsonified_request + assert jsonified_request["query"] == "query_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -20054,7 +21921,7 @@ def test_search_messages_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = message.SearchMessagesResponse() + return_value = space.SearchSpacesResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -20066,89 +21933,36 @@ def test_search_messages_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = message.SearchMessagesResponse.pb(return_value) + return_value = space.SearchSpacesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.search_messages(request) + response = client.search_spaces(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "query", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_search_messages_rest_flattened(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = message.SearchMessagesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "spaces/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - filter="filter_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = message.SearchMessagesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.search_messages(**mock_args) - - # Establish that the underlying call 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=spaces/*}/messages:search" % client.transport._host, args[1] - ) - - -def test_search_messages_rest_flattened_error(transport: str = "rest"): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.search_messages( - message.SearchMessagesRequest(), - parent="parent_value", - filter="filter_value", - ) - - -def test_search_messages_rest_pager(transport: str = "rest"): +def test_search_spaces_rest_pager(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -20160,28 +21974,28 @@ def test_search_messages_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - message.SearchMessagesResponse( - results=[ - message.SearchMessageResult(), - message.SearchMessageResult(), - message.SearchMessageResult(), + space.SearchSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + space.Space(), ], next_page_token="abc", ), - message.SearchMessagesResponse( - results=[], + space.SearchSpacesResponse( + spaces=[], next_page_token="def", ), - message.SearchMessagesResponse( - results=[ - message.SearchMessageResult(), + space.SearchSpacesResponse( + spaces=[ + space.Space(), ], next_page_token="ghi", ), - message.SearchMessagesResponse( - results=[ - message.SearchMessageResult(), - message.SearchMessageResult(), + space.SearchSpacesResponse( + spaces=[ + space.Space(), + space.Space(), ], ), ) @@ -20189,30 +22003,30 @@ def test_search_messages_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple(message.SearchMessagesResponse.to_json(x) for x in response) + response = tuple(space.SearchSpacesResponse.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": "spaces/sample1"} + sample_request = {} - pager = client.search_messages(request=sample_request) + pager = client.search_spaces(request=sample_request) assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") results = list(pager) assert len(results) == 6 - assert all(isinstance(i, message.SearchMessageResult) for i in results) + assert all(isinstance(i, space.Space) for i in results) - pages = list(client.search_messages(request=sample_request).pages) + pages = list(client.search_spaces(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_get_attachment_rest_use_cached_wrapped_rpc(): +def test_get_space_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -20226,31 +22040,29 @@ def test_get_attachment_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_attachment in client._transport._wrapped_methods + assert client._transport.get_space in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_attachment] = mock_rpc + client._transport._wrapped_methods[client._transport.get_space] = mock_rpc request = {} - client.get_attachment(request) + client.get_space(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_attachment(request) + client.get_space(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_attachment_rest_required_fields( - request_type=attachment.GetAttachmentRequest, -): +def test_get_space_rest_required_fields(request_type=space.GetSpaceRequest): transport_class = transports.ChatServiceRestTransport request_init = {} @@ -20264,8 +22076,8 @@ def test_get_attachment_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetAttachment, - "_BaseGetAttachment__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetSpace, + "_BaseGetSpace__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -20277,6 +22089,9 @@ def test_get_attachment_rest_required_fields( jsonified_request["name"] = "name_value" + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("useAdminAccess",)) + # verify required fields with non-default values are left alone assert "name" in jsonified_request assert jsonified_request["name"] == "name_value" @@ -20288,7 +22103,7 @@ def test_get_attachment_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = attachment.Attachment() + return_value = space.Space() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -20309,21 +22124,21 @@ def test_get_attachment_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = attachment.Attachment.pb(return_value) + return_value = space.Space.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_attachment(request) + response = client.get_space(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_attachment_rest_flattened(): +def test_get_space_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -20332,10 +22147,10 @@ def test_get_attachment_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = attachment.Attachment() + return_value = space.Space() # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1/messages/sample2/attachments/sample3"} + sample_request = {"name": "spaces/sample1"} # get truthy value for each flattened field mock_args = dict( @@ -20347,25 +22162,24 @@ def test_get_attachment_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = attachment.Attachment.pb(return_value) + return_value = space.Space.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_attachment(**mock_args) + client.get_space(**mock_args) # Establish that the underlying call 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=spaces/*/messages/*/attachments/*}" % client.transport._host, - args[1], + "%s/v1/{name=spaces/*}" % client.transport._host, args[1] ) -def test_get_attachment_rest_flattened_error(transport: str = "rest"): +def test_get_space_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -20374,13 +22188,13 @@ def test_get_attachment_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_attachment( - attachment.GetAttachmentRequest(), + client.get_space( + space.GetSpaceRequest(), name="name_value", ) -def test_upload_attachment_rest_use_cached_wrapped_rpc(): +def test_create_space_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -20394,38 +22208,32 @@ def test_upload_attachment_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.upload_attachment in client._transport._wrapped_methods + assert client._transport.create_space in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.upload_attachment] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.create_space] = mock_rpc request = {} - client.upload_attachment(request) + client.create_space(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.upload_attachment(request) + client.create_space(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_upload_attachment_rest_required_fields( - request_type=attachment.UploadAttachmentRequest, -): +def test_create_space_rest_required_fields(request_type=gc_space.CreateSpaceRequest): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["parent"] = "" - request_init["filename"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -20435,8 +22243,8 @@ def test_upload_attachment_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseUploadAttachment, - "_BaseUploadAttachment__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseCreateSpace, + "_BaseCreateSpace__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -20446,14 +22254,10 @@ def test_upload_attachment_rest_required_fields( # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - jsonified_request["filename"] = "filename_value" + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("requestId",)) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "filename" in jsonified_request - assert jsonified_request["filename"] == "filename_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -20462,7 +22266,7 @@ def test_upload_attachment_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = attachment.UploadAttachmentResponse() + return_value = gc_space.Space() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -20484,21 +22288,75 @@ def test_upload_attachment_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = attachment.UploadAttachmentResponse.pb(return_value) + return_value = gc_space.Space.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.upload_attachment(request) + response = client.create_space(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_spaces_rest_use_cached_wrapped_rpc(): +def test_create_space_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gc_space.Space() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + space=gc_space.Space(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_space(**mock_args) + + # Establish that the underlying call 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/spaces" % client.transport._host, args[1]) + + +def test_create_space_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.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_space( + gc_space.CreateSpaceRequest(), + space=gc_space.Space(name="name_value"), + ) + + +def test_set_up_space_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -20512,93 +22370,98 @@ def test_list_spaces_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_spaces in client._transport._wrapped_methods + assert client._transport.set_up_space in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_spaces] = mock_rpc + client._transport._wrapped_methods[client._transport.set_up_space] = mock_rpc request = {} - client.list_spaces(request) + client.set_up_space(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_spaces(request) + client.set_up_space(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_spaces_rest_pager(transport: str = "rest"): +def test_set_up_space_rest_required_fields(request_type=space_setup.SetUpSpaceRequest): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseSetUpSpace, + "_BaseSetUpSpace__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # verify required fields with non-default values are left alone + client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) + request = request_type(**request_init) + # Designate an appropriate value for the returned response. + return_value = space.Space() # 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 = ( - space.ListSpacesResponse( - spaces=[ - space.Space(), - space.Space(), - space.Space(), - ], - next_page_token="abc", - ), - space.ListSpacesResponse( - spaces=[], - next_page_token="def", - ), - space.ListSpacesResponse( - spaces=[ - space.Space(), - ], - next_page_token="ghi", - ), - space.ListSpacesResponse( - spaces=[ - space.Space(), - space.Space(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(space.ListSpacesResponse.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 + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 - sample_request = {} + response_value = Response() + response_value.status_code = 200 - pager = client.list_spaces(request=sample_request) + # Convert return value to protobuf type + return_value = space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, space.Space) for i in results) + response = client.set_up_space(request) - pages = list(client.list_spaces(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -def test_search_spaces_rest_use_cached_wrapped_rpc(): +def test_update_space_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -20612,33 +22475,32 @@ def test_search_spaces_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.search_spaces in client._transport._wrapped_methods + assert client._transport.update_space in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.search_spaces] = mock_rpc + client._transport._wrapped_methods[client._transport.update_space] = mock_rpc request = {} - client.search_spaces(request) + client.update_space(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.search_spaces(request) + client.update_space(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_search_spaces_rest_required_fields(request_type=space.SearchSpacesRequest): +def test_update_space_rest_required_fields(request_type=gc_space.UpdateSpaceRequest): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["query"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -20646,11 +22508,10 @@ def test_search_spaces_rest_required_fields(request_type=space.SearchSpacesReque ) # verify fields with default values are dropped - assert "query" not in jsonified_request default_values = getattr( - transport_class._BaseSearchSpaces, - "_BaseSearchSpaces__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseUpdateSpace, + "_BaseUpdateSpace__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -20659,25 +22520,16 @@ def test_search_spaces_rest_required_fields(request_type=space.SearchSpacesReque jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "query" in jsonified_request - assert jsonified_request["query"] == request_init["query"] - - jsonified_request["query"] = "query_value" # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "orderBy", - "pageSize", - "pageToken", - "query", + "updateMask", "useAdminAccess", ) ) # verify required fields with non-default values are left alone - assert "query" in jsonified_request - assert jsonified_request["query"] == "query_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -20686,7 +22538,7 @@ def test_search_spaces_rest_required_fields(request_type=space.SearchSpacesReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = space.SearchSpacesResponse() + return_value = gc_space.Space() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -20698,100 +22550,89 @@ def test_search_spaces_rest_required_fields(request_type=space.SearchSpacesReque pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = space.SearchSpacesResponse.pb(return_value) + return_value = gc_space.Space.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.search_spaces(request) + response = client.update_space(request) - expected_params = [ - ( - "query", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_search_spaces_rest_pager(transport: str = "rest"): +def test_update_space_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - space.SearchSpacesResponse( - spaces=[ - space.Space(), - space.Space(), - space.Space(), - ], - next_page_token="abc", - ), - space.SearchSpacesResponse( - spaces=[], - next_page_token="def", - ), - space.SearchSpacesResponse( - spaces=[ - space.Space(), - ], - next_page_token="ghi", - ), - space.SearchSpacesResponse( - spaces=[ - space.Space(), - space.Space(), - ], - ), + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gc_space.Space() + + # get arguments that satisfy an http rule for this method + sample_request = {"space": {"name": "spaces/sample1"}} + + # get truthy value for each flattened field + mock_args = dict( + space=gc_space.Space(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - # Two responses for two calls - response = response + response + mock_args.update(sample_request) - # Wrap the values into proper Response objs - response = tuple(space.SearchSpacesResponse.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 + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - sample_request = {} + client.update_space(**mock_args) - pager = client.search_spaces(request=sample_request) + # Establish that the underlying call 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/{space.name=spaces/*}" % client.transport._host, args[1] + ) - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, space.Space) for i in results) +def test_update_space_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - pages = list(client.search_spaces(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_space( + gc_space.UpdateSpaceRequest(), + space=gc_space.Space(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) -def test_get_space_rest_use_cached_wrapped_rpc(): +def test_delete_space_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -20805,29 +22646,29 @@ def test_get_space_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_space in client._transport._wrapped_methods + assert client._transport.delete_space in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_space] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_space] = mock_rpc request = {} - client.get_space(request) + client.delete_space(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_space(request) + client.delete_space(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_space_rest_required_fields(request_type=space.GetSpaceRequest): +def test_delete_space_rest_required_fields(request_type=space.DeleteSpaceRequest): transport_class = transports.ChatServiceRestTransport request_init = {} @@ -20841,8 +22682,8 @@ def test_get_space_rest_required_fields(request_type=space.GetSpaceRequest): # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetSpace, - "_BaseGetSpace__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseDeleteSpace, + "_BaseDeleteSpace__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -20868,7 +22709,7 @@ def test_get_space_rest_required_fields(request_type=space.GetSpaceRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = space.Space() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -20880,30 +22721,27 @@ def test_get_space_rest_required_fields(request_type=space.GetSpaceRequest): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "delete", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = space.Space.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_space(request) + response = client.delete_space(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_space_rest_flattened(): +def test_delete_space_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -20912,7 +22750,7 @@ def test_get_space_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = space.Space() + return_value = None # get arguments that satisfy an http rule for this method sample_request = {"name": "spaces/sample1"} @@ -20926,14 +22764,12 @@ def test_get_space_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = space.Space.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_space(**mock_args) + client.delete_space(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -20944,7 +22780,7 @@ def test_get_space_rest_flattened(): ) -def test_get_space_rest_flattened_error(transport: str = "rest"): +def test_delete_space_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -20953,13 +22789,13 @@ def test_get_space_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_space( - space.GetSpaceRequest(), + client.delete_space( + space.DeleteSpaceRequest(), name="name_value", ) -def test_create_space_rest_use_cached_wrapped_rpc(): +def test_complete_import_space_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -20973,32 +22809,40 @@ def test_create_space_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_space in client._transport._wrapped_methods + assert ( + client._transport.complete_import_space + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_space] = mock_rpc + client._transport._wrapped_methods[client._transport.complete_import_space] = ( + mock_rpc + ) request = {} - client.create_space(request) + client.complete_import_space(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_space(request) + client.complete_import_space(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_space_rest_required_fields(request_type=gc_space.CreateSpaceRequest): +def test_complete_import_space_rest_required_fields( + request_type=space.CompleteImportSpaceRequest, +): transport_class = transports.ChatServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -21008,8 +22852,8 @@ def test_create_space_rest_required_fields(request_type=gc_space.CreateSpaceRequ # verify fields with default values are dropped default_values = getattr( - transport_class._BaseCreateSpace, - "_BaseCreateSpace__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseCompleteImportSpace, + "_BaseCompleteImportSpace__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -21019,10 +22863,11 @@ def test_create_space_rest_required_fields(request_type=gc_space.CreateSpaceRequ # verify required fields with default values are now present - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("requestId",)) + jsonified_request["name"] = "name_value" # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -21031,7 +22876,7 @@ def test_create_space_rest_required_fields(request_type=gc_space.CreateSpaceRequ request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gc_space.Space() + return_value = space.CompleteImportSpaceResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -21053,75 +22898,21 @@ def test_create_space_rest_required_fields(request_type=gc_space.CreateSpaceRequ response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_space.Space.pb(return_value) + return_value = space.CompleteImportSpaceResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_space(request) + response = client.complete_import_space(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_space_rest_flattened(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = gc_space.Space() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - space=gc_space.Space(name="name_value"), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gc_space.Space.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_space(**mock_args) - - # Establish that the underlying call 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/spaces" % client.transport._host, args[1]) - - -def test_create_space_rest_flattened_error(transport: str = "rest"): - client = ChatServiceClient( - credentials=ga_credentials.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_space( - gc_space.CreateSpaceRequest(), - space=gc_space.Space(name="name_value"), - ) - - -def test_set_up_space_rest_use_cached_wrapped_rpc(): +def test_find_direct_message_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -21135,32 +22926,39 @@ def test_set_up_space_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.set_up_space in client._transport._wrapped_methods + assert ( + client._transport.find_direct_message in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.set_up_space] = mock_rpc + client._transport._wrapped_methods[client._transport.find_direct_message] = ( + mock_rpc + ) request = {} - client.set_up_space(request) + client.find_direct_message(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.set_up_space(request) + client.find_direct_message(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_set_up_space_rest_required_fields(request_type=space_setup.SetUpSpaceRequest): +def test_find_direct_message_rest_required_fields( + request_type=space.FindDirectMessageRequest, +): transport_class = transports.ChatServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -21168,10 +22966,11 @@ def test_set_up_space_rest_required_fields(request_type=space_setup.SetUpSpaceRe ) # verify fields with default values are dropped + assert "name" not in jsonified_request default_values = getattr( - transport_class._BaseSetUpSpace, - "_BaseSetUpSpace__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseFindDirectMessage, + "_BaseFindDirectMessage__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -21180,8 +22979,17 @@ def test_set_up_space_rest_required_fields(request_type=space_setup.SetUpSpaceRe jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "name" in jsonified_request + assert jsonified_request["name"] == request_init["name"] + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("name",)) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -21202,10 +23010,9 @@ def test_set_up_space_rest_required_fields(request_type=space_setup.SetUpSpaceRe pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -21219,14 +23026,20 @@ def test_set_up_space_rest_required_fields(request_type=space_setup.SetUpSpaceRe req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.set_up_space(request) + response = client.find_direct_message(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "name", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_space_rest_use_cached_wrapped_rpc(): +def test_find_group_chats_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -21240,32 +23053,139 @@ def test_update_space_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_space in client._transport._wrapped_methods + assert client._transport.find_group_chats in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_space] = mock_rpc + client._transport._wrapped_methods[client._transport.find_group_chats] = ( + mock_rpc + ) request = {} - client.update_space(request) + client.find_group_chats(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_space(request) + client.find_group_chats(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_space_rest_required_fields(request_type=gc_space.UpdateSpaceRequest): +def test_find_group_chats_rest_pager(transport: str = "rest"): + client = ChatServiceClient( + 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 = ( + space.FindGroupChatsResponse( + spaces=[ + space.Space(), + space.Space(), + space.Space(), + ], + next_page_token="abc", + ), + space.FindGroupChatsResponse( + spaces=[], + next_page_token="def", + ), + space.FindGroupChatsResponse( + spaces=[ + space.Space(), + ], + next_page_token="ghi", + ), + space.FindGroupChatsResponse( + spaces=[ + space.Space(), + space.Space(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(space.FindGroupChatsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {} + + pager = client.find_group_chats(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, space.Space) for i in results) + + pages = list(client.find_group_chats(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_membership_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_membership in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_membership] = ( + mock_rpc + ) + + request = {} + client.create_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_membership(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_membership_rest_required_fields( + request_type=gc_membership.CreateMembershipRequest, +): transport_class = transports.ChatServiceRestTransport request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -21275,8 +23195,8 @@ def test_update_space_rest_required_fields(request_type=gc_space.UpdateSpaceRequ # verify fields with default values are dropped default_values = getattr( - transport_class._BaseUpdateSpace, - "_BaseUpdateSpace__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseCreateMembership, + "_BaseCreateMembership__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -21286,15 +23206,14 @@ def test_update_space_rest_required_fields(request_type=gc_space.UpdateSpaceRequ # verify required fields with default values are now present + jsonified_request["parent"] = "parent_value" + # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "updateMask", - "useAdminAccess", - ) - ) + assert not set(unset_fields) - set(("useAdminAccess",)) # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -21303,7 +23222,7 @@ def test_update_space_rest_required_fields(request_type=gc_space.UpdateSpaceRequ request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gc_space.Space() + return_value = gc_membership.Membership() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -21315,7 +23234,7 @@ def test_update_space_rest_required_fields(request_type=gc_space.UpdateSpaceRequ pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -21325,21 +23244,21 @@ def test_update_space_rest_required_fields(request_type=gc_space.UpdateSpaceRequ response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_space.Space.pb(return_value) + return_value = gc_membership.Membership.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_space(request) + response = client.create_membership(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_space_rest_flattened(): +def test_create_membership_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -21348,15 +23267,15 @@ def test_update_space_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gc_space.Space() + return_value = gc_membership.Membership() # get arguments that satisfy an http rule for this method - sample_request = {"space": {"name": "spaces/sample1"}} + sample_request = {"parent": "spaces/sample1"} # get truthy value for each flattened field mock_args = dict( - space=gc_space.Space(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + parent="parent_value", + membership=gc_membership.Membership(name="name_value"), ) mock_args.update(sample_request) @@ -21364,24 +23283,24 @@ def test_update_space_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_space.Space.pb(return_value) + return_value = gc_membership.Membership.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_space(**mock_args) + client.create_membership(**mock_args) # Establish that the underlying call 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/{space.name=spaces/*}" % client.transport._host, args[1] + "%s/v1/{parent=spaces/*}/members" % client.transport._host, args[1] ) -def test_update_space_rest_flattened_error(transport: str = "rest"): +def test_create_membership_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -21390,14 +23309,14 @@ def test_update_space_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_space( - gc_space.UpdateSpaceRequest(), - space=gc_space.Space(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.create_membership( + gc_membership.CreateMembershipRequest(), + parent="parent_value", + membership=gc_membership.Membership(name="name_value"), ) -def test_delete_space_rest_use_cached_wrapped_rpc(): +def test_update_membership_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -21411,33 +23330,36 @@ def test_delete_space_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_space in client._transport._wrapped_methods + assert client._transport.update_membership in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_space] = mock_rpc + client._transport._wrapped_methods[client._transport.update_membership] = ( + mock_rpc + ) request = {} - client.delete_space(request) + client.update_membership(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_space(request) + client.update_membership(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_space_rest_required_fields(request_type=space.DeleteSpaceRequest): +def test_update_membership_rest_required_fields( + request_type=gc_membership.UpdateMembershipRequest, +): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -21447,8 +23369,8 @@ def test_delete_space_rest_required_fields(request_type=space.DeleteSpaceRequest # verify fields with default values are dropped default_values = getattr( - transport_class._BaseDeleteSpace, - "_BaseDeleteSpace__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseUpdateMembership, + "_BaseUpdateMembership__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -21458,14 +23380,15 @@ def test_delete_space_rest_required_fields(request_type=space.DeleteSpaceRequest # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("useAdminAccess",)) + assert not set(unset_fields) - set( + ( + "updateMask", + "useAdminAccess", + ) + ) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -21474,7 +23397,7 @@ def test_delete_space_rest_required_fields(request_type=space.DeleteSpaceRequest request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = gc_membership.Membership() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -21486,27 +23409,31 @@ def test_delete_space_rest_required_fields(request_type=space.DeleteSpaceRequest pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "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 = "" + + # Convert return value to protobuf type + return_value = gc_membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_space(request) + response = client.update_membership(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_space_rest_flattened(): +def test_update_membership_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -21515,37 +23442,41 @@ def test_delete_space_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = gc_membership.Membership() # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1"} + sample_request = {"membership": {"name": "spaces/sample1/members/sample2"}} # get truthy value for each flattened field mock_args = dict( - name="name_value", + membership=gc_membership.Membership(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 = "" + # Convert return value to protobuf type + return_value = gc_membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_space(**mock_args) + client.update_membership(**mock_args) # Establish that the underlying call 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=spaces/*}" % client.transport._host, args[1] + "%s/v1/{membership.name=spaces/*/members/*}" % client.transport._host, + args[1], ) -def test_delete_space_rest_flattened_error(transport: str = "rest"): +def test_update_membership_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -21554,13 +23485,14 @@ def test_delete_space_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_space( - space.DeleteSpaceRequest(), - name="name_value", + client.update_membership( + gc_membership.UpdateMembershipRequest(), + membership=gc_membership.Membership(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_complete_import_space_rest_use_cached_wrapped_rpc(): +def test_delete_membership_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -21574,35 +23506,32 @@ def test_complete_import_space_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.complete_import_space - in client._transport._wrapped_methods - ) + assert client._transport.delete_membership in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.complete_import_space] = ( + client._transport._wrapped_methods[client._transport.delete_membership] = ( mock_rpc ) request = {} - client.complete_import_space(request) + client.delete_membership(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.complete_import_space(request) + client.delete_membership(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_complete_import_space_rest_required_fields( - request_type=space.CompleteImportSpaceRequest, +def test_delete_membership_rest_required_fields( + request_type=membership.DeleteMembershipRequest, ): transport_class = transports.ChatServiceRestTransport @@ -21617,8 +23546,8 @@ def test_complete_import_space_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseCompleteImportSpace, - "_BaseCompleteImportSpace__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseDeleteMembership, + "_BaseDeleteMembership__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -21630,6 +23559,9 @@ def test_complete_import_space_rest_required_fields( jsonified_request["name"] = "name_value" + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("useAdminAccess",)) + # verify required fields with non-default values are left alone assert "name" in jsonified_request assert jsonified_request["name"] == "name_value" @@ -21641,7 +23573,7 @@ def test_complete_import_space_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = space.CompleteImportSpaceResponse() + return_value = membership.Membership() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -21653,31 +23585,86 @@ def test_complete_import_space_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result - response_value = Response() - response_value.status_code = 200 + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_membership(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_membership_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = membership.Membership() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "spaces/sample1/members/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_membership(**mock_args) - # Convert return value to protobuf type - return_value = space.CompleteImportSpaceResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=spaces/*/members/*}" % client.transport._host, args[1] + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.complete_import_space(request) +def test_delete_membership_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_membership( + membership.DeleteMembershipRequest(), + name="name_value", + ) -def test_find_direct_message_rest_use_cached_wrapped_rpc(): +def test_create_reaction_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -21691,39 +23678,35 @@ def test_find_direct_message_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.find_direct_message in client._transport._wrapped_methods - ) + assert client._transport.create_reaction in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.find_direct_message] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.create_reaction] = mock_rpc request = {} - client.find_direct_message(request) + client.create_reaction(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.find_direct_message(request) + client.create_reaction(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_find_direct_message_rest_required_fields( - request_type=space.FindDirectMessageRequest, +def test_create_reaction_rest_required_fields( + request_type=gc_reaction.CreateReactionRequest, ): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -21731,11 +23714,10 @@ def test_find_direct_message_rest_required_fields( ) # verify fields with default values are dropped - assert "name" not in jsonified_request default_values = getattr( - transport_class._BaseFindDirectMessage, - "_BaseFindDirectMessage__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseCreateReaction, + "_BaseCreateReaction__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -21744,17 +23726,12 @@ def test_find_direct_message_rest_required_fields( jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "name" in jsonified_request - assert jsonified_request["name"] == request_init["name"] - jsonified_request["name"] = "name_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("name",)) + jsonified_request["parent"] = "parent_value" # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -21763,7 +23740,7 @@ def test_find_direct_message_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = space.Space() + return_value = gc_reaction.Reaction() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -21775,138 +23752,90 @@ def test_find_direct_message_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = space.Space.pb(return_value) + return_value = gc_reaction.Reaction.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.find_direct_message(request) + response = client.create_reaction(request) - expected_params = [ - ( - "name", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_find_group_chats_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_create_reaction_rest_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gc_reaction.Reaction() - # Ensure method has been cached - assert client._transport.find_group_chats in client._transport._wrapped_methods + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "spaces/sample1/messages/sample2"} - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.find_group_chats] = ( - mock_rpc + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + reaction=gc_reaction.Reaction(name="name_value"), ) + mock_args.update(sample_request) - request = {} - client.find_group_chats(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_reaction.Reaction.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.find_group_chats(request) + client.create_reaction(**mock_args) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # Establish that the underlying call 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=spaces/*/messages/*}/reactions" % client.transport._host, + args[1], + ) -def test_find_group_chats_rest_pager(transport: str = "rest"): +def test_create_reaction_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( 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 = ( - space.FindGroupChatsResponse( - spaces=[ - space.Space(), - space.Space(), - space.Space(), - ], - next_page_token="abc", - ), - space.FindGroupChatsResponse( - spaces=[], - next_page_token="def", - ), - space.FindGroupChatsResponse( - spaces=[ - space.Space(), - ], - next_page_token="ghi", - ), - space.FindGroupChatsResponse( - spaces=[ - space.Space(), - space.Space(), - ], - ), + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_reaction( + gc_reaction.CreateReactionRequest(), + parent="parent_value", + reaction=gc_reaction.Reaction(name="name_value"), ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(space.FindGroupChatsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {} - - pager = client.find_group_chats(request=sample_request) - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, space.Space) for i in results) - - pages = list(client.find_group_chats(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token -def test_create_membership_rest_use_cached_wrapped_rpc(): +def test_list_reactions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -21920,32 +23849,30 @@ def test_create_membership_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_membership in client._transport._wrapped_methods + assert client._transport.list_reactions in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_membership] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.list_reactions] = mock_rpc request = {} - client.create_membership(request) + client.list_reactions(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_membership(request) + client.list_reactions(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_membership_rest_required_fields( - request_type=gc_membership.CreateMembershipRequest, +def test_list_reactions_rest_required_fields( + request_type=reaction.ListReactionsRequest, ): transport_class = transports.ChatServiceRestTransport @@ -21960,8 +23887,8 @@ def test_create_membership_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseCreateMembership, - "_BaseCreateMembership__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListReactions, + "_BaseListReactions__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -21974,7 +23901,13 @@ def test_create_membership_rest_required_fields( jsonified_request["parent"] = "parent_value" # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("useAdminAccess",)) + assert not set(unset_fields) - set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) # verify required fields with non-default values are left alone assert "parent" in jsonified_request @@ -21987,7 +23920,7 @@ def test_create_membership_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gc_membership.Membership() + return_value = reaction.ListReactionsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -21999,31 +23932,30 @@ def test_create_membership_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_membership.Membership.pb(return_value) + return_value = reaction.ListReactionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_membership(request) + response = client.list_reactions(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_membership_rest_flattened(): +def test_list_reactions_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -22032,15 +23964,14 @@ def test_create_membership_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gc_membership.Membership() + return_value = reaction.ListReactionsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "spaces/sample1"} + sample_request = {"parent": "spaces/sample1/messages/sample2"} # get truthy value for each flattened field mock_args = dict( parent="parent_value", - membership=gc_membership.Membership(name="name_value"), ) mock_args.update(sample_request) @@ -22048,24 +23979,25 @@ def test_create_membership_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_membership.Membership.pb(return_value) + return_value = reaction.ListReactionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_membership(**mock_args) + client.list_reactions(**mock_args) # Establish that the underlying call 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=spaces/*}/members" % client.transport._host, args[1] + "%s/v1/{parent=spaces/*/messages/*}/reactions" % client.transport._host, + args[1], ) -def test_create_membership_rest_flattened_error(transport: str = "rest"): +def test_list_reactions_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -22074,14 +24006,77 @@ def test_create_membership_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_membership( - gc_membership.CreateMembershipRequest(), + client.list_reactions( + reaction.ListReactionsRequest(), parent="parent_value", - membership=gc_membership.Membership(name="name_value"), ) -def test_update_membership_rest_use_cached_wrapped_rpc(): +def test_list_reactions_rest_pager(transport: str = "rest"): + client = ChatServiceClient( + 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 = ( + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + reaction.Reaction(), + ], + next_page_token="abc", + ), + reaction.ListReactionsResponse( + reactions=[], + next_page_token="def", + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + ], + next_page_token="ghi", + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(reaction.ListReactionsResponse.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": "spaces/sample1/messages/sample2"} + + pager = client.list_reactions(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, reaction.Reaction) for i in results) + + pages = list(client.list_reactions(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_reaction_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -22095,36 +24090,35 @@ def test_update_membership_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_membership in client._transport._wrapped_methods + assert client._transport.delete_reaction in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_membership] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.delete_reaction] = mock_rpc request = {} - client.update_membership(request) + client.delete_reaction(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_membership(request) + client.delete_reaction(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_membership_rest_required_fields( - request_type=gc_membership.UpdateMembershipRequest, +def test_delete_reaction_rest_required_fields( + request_type=reaction.DeleteReactionRequest, ): transport_class = transports.ChatServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -22134,8 +24128,8 @@ def test_update_membership_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseUpdateMembership, - "_BaseUpdateMembership__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseDeleteReaction, + "_BaseDeleteReaction__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -22145,15 +24139,11 @@ def test_update_membership_rest_required_fields( # verify required fields with default values are now present - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "updateMask", - "useAdminAccess", - ) - ) + jsonified_request["name"] = "name_value" # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -22162,7 +24152,7 @@ def test_update_membership_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gc_membership.Membership() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -22174,31 +24164,27 @@ def test_update_membership_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gc_membership.Membership.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_membership(request) + response = client.delete_reaction(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_membership_rest_flattened(): +def test_delete_reaction_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -22207,41 +24193,38 @@ def test_update_membership_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gc_membership.Membership() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"membership": {"name": "spaces/sample1/members/sample2"}} + sample_request = {"name": "spaces/sample1/messages/sample2/reactions/sample3"} # get truthy value for each flattened field mock_args = dict( - membership=gc_membership.Membership(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gc_membership.Membership.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_membership(**mock_args) + client.delete_reaction(**mock_args) # Establish that the underlying call 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/{membership.name=spaces/*/members/*}" % client.transport._host, + "%s/v1/{name=spaces/*/messages/*/reactions/*}" % client.transport._host, args[1], ) -def test_update_membership_rest_flattened_error(transport: str = "rest"): +def test_delete_reaction_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -22250,14 +24233,13 @@ def test_update_membership_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_membership( - gc_membership.UpdateMembershipRequest(), - membership=gc_membership.Membership(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_reaction( + reaction.DeleteReactionRequest(), + name="name_value", ) -def test_delete_membership_rest_use_cached_wrapped_rpc(): +def test_list_message_pins_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -22271,37 +24253,37 @@ def test_delete_membership_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_membership in client._transport._wrapped_methods + assert client._transport.list_message_pins in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_membership] = ( + client._transport._wrapped_methods[client._transport.list_message_pins] = ( mock_rpc ) request = {} - client.delete_membership(request) + client.list_message_pins(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_membership(request) + client.list_message_pins(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_membership_rest_required_fields( - request_type=membership.DeleteMembershipRequest, +def test_list_message_pins_rest_required_fields( + request_type=message_pin.ListMessagePinsRequest, ): transport_class = transports.ChatServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -22311,8 +24293,8 @@ def test_delete_membership_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseDeleteMembership, - "_BaseDeleteMembership__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListMessagePins, + "_BaseListMessagePins__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -22322,14 +24304,19 @@ def test_delete_membership_rest_required_fields( # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("useAdminAccess",)) + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + ) + ) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -22338,7 +24325,7 @@ def test_delete_membership_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = membership.Membership() + return_value = message_pin.ListMessagePinsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -22350,7 +24337,7 @@ def test_delete_membership_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "get", "query_params": pb_request, } transcode.return_value = transcode_result @@ -22359,21 +24346,21 @@ def test_delete_membership_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = membership.Membership.pb(return_value) + return_value = message_pin.ListMessagePinsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_membership(request) + response = client.list_message_pins(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_membership_rest_flattened(): +def test_list_message_pins_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -22382,14 +24369,14 @@ def test_delete_membership_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = membership.Membership() + return_value = message_pin.ListMessagePinsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1/members/sample2"} + sample_request = {"parent": "spaces/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) @@ -22397,24 +24384,24 @@ def test_delete_membership_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = membership.Membership.pb(return_value) + return_value = message_pin.ListMessagePinsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_membership(**mock_args) + client.list_message_pins(**mock_args) # Establish that the underlying call 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=spaces/*/members/*}" % client.transport._host, args[1] + "%s/v1/{parent=spaces/*}/messagePins" % client.transport._host, args[1] ) -def test_delete_membership_rest_flattened_error(transport: str = "rest"): +def test_list_message_pins_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -22423,13 +24410,79 @@ def test_delete_membership_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_membership( - membership.DeleteMembershipRequest(), - name="name_value", + client.list_message_pins( + message_pin.ListMessagePinsRequest(), + parent="parent_value", ) -def test_create_reaction_rest_use_cached_wrapped_rpc(): +def test_list_message_pins_rest_pager(transport: str = "rest"): + client = ChatServiceClient( + 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 = ( + message_pin.ListMessagePinsResponse( + message_pins=[ + message_pin.MessagePin(), + message_pin.MessagePin(), + message_pin.MessagePin(), + ], + next_page_token="abc", + ), + message_pin.ListMessagePinsResponse( + message_pins=[], + next_page_token="def", + ), + message_pin.ListMessagePinsResponse( + message_pins=[ + message_pin.MessagePin(), + ], + next_page_token="ghi", + ), + message_pin.ListMessagePinsResponse( + message_pins=[ + message_pin.MessagePin(), + message_pin.MessagePin(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + message_pin.ListMessagePinsResponse.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": "spaces/sample1"} + + pager = client.list_message_pins(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, message_pin.MessagePin) for i in results) + + pages = list(client.list_message_pins(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_message_pin_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -22443,30 +24496,34 @@ def test_create_reaction_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_reaction in client._transport._wrapped_methods + assert ( + client._transport.create_message_pin in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_reaction] = mock_rpc + client._transport._wrapped_methods[client._transport.create_message_pin] = ( + mock_rpc + ) request = {} - client.create_reaction(request) + client.create_message_pin(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_reaction(request) + client.create_message_pin(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_reaction_rest_required_fields( - request_type=gc_reaction.CreateReactionRequest, +def test_create_message_pin_rest_required_fields( + request_type=gc_message_pin.CreateMessagePinRequest, ): transport_class = transports.ChatServiceRestTransport @@ -22481,8 +24538,8 @@ def test_create_reaction_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseCreateReaction, - "_BaseCreateReaction__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseCreateMessagePin, + "_BaseCreateMessagePin__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -22505,7 +24562,7 @@ def test_create_reaction_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gc_reaction.Reaction() + return_value = gc_message_pin.MessagePin() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -22527,21 +24584,21 @@ def test_create_reaction_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_reaction.Reaction.pb(return_value) + return_value = gc_message_pin.MessagePin.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_reaction(request) + response = client.create_message_pin(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_reaction_rest_flattened(): +def test_create_message_pin_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -22550,15 +24607,15 @@ def test_create_reaction_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gc_reaction.Reaction() + return_value = gc_message_pin.MessagePin() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "spaces/sample1/messages/sample2"} + sample_request = {"parent": "spaces/sample1"} # get truthy value for each flattened field mock_args = dict( parent="parent_value", - reaction=gc_reaction.Reaction(name="name_value"), + message_pin=gc_message_pin.MessagePin(name="name_value"), ) mock_args.update(sample_request) @@ -22566,25 +24623,24 @@ def test_create_reaction_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_reaction.Reaction.pb(return_value) + return_value = gc_message_pin.MessagePin.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_reaction(**mock_args) + client.create_message_pin(**mock_args) # Establish that the underlying call 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=spaces/*/messages/*}/reactions" % client.transport._host, - args[1], + "%s/v1/{parent=spaces/*}/messagePins" % client.transport._host, args[1] ) -def test_create_reaction_rest_flattened_error(transport: str = "rest"): +def test_create_message_pin_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -22593,14 +24649,14 @@ def test_create_reaction_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_reaction( - gc_reaction.CreateReactionRequest(), + client.create_message_pin( + gc_message_pin.CreateMessagePinRequest(), parent="parent_value", - reaction=gc_reaction.Reaction(name="name_value"), + message_pin=gc_message_pin.MessagePin(name="name_value"), ) -def test_list_reactions_rest_use_cached_wrapped_rpc(): +def test_delete_message_pin_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -22614,271 +24670,34 @@ def test_list_reactions_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_reactions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.list_reactions] = mock_rpc - - request = {} - client.list_reactions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_reactions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_reactions_rest_required_fields( - request_type=reaction.ListReactionsRequest, -): - transport_class = transports.ChatServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - default_values = getattr( - transport_class._BaseListReactions, - "_BaseListReactions__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = "parent_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "pageSize", - "pageToken", - ) - ) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = reaction.ListReactionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = reaction.ListReactionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_reactions(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) - - -def test_list_reactions_rest_flattened(): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = reaction.ListReactionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "spaces/sample1/messages/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = reaction.ListReactionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_reactions(**mock_args) - - # Establish that the underlying call 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=spaces/*/messages/*}/reactions" % client.transport._host, - args[1], - ) - - -def test_list_reactions_rest_flattened_error(transport: str = "rest"): - client = ChatServiceClient( - credentials=ga_credentials.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_reactions( - reaction.ListReactionsRequest(), - parent="parent_value", - ) - - -def test_list_reactions_rest_pager(transport: str = "rest"): - client = ChatServiceClient( - 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 = ( - reaction.ListReactionsResponse( - reactions=[ - reaction.Reaction(), - reaction.Reaction(), - reaction.Reaction(), - ], - next_page_token="abc", - ), - reaction.ListReactionsResponse( - reactions=[], - next_page_token="def", - ), - reaction.ListReactionsResponse( - reactions=[ - reaction.Reaction(), - ], - next_page_token="ghi", - ), - reaction.ListReactionsResponse( - reactions=[ - reaction.Reaction(), - reaction.Reaction(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(reaction.ListReactionsResponse.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": "spaces/sample1/messages/sample2"} - - pager = client.list_reactions(request=sample_request) - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, reaction.Reaction) for i in results) - - pages = list(client.list_reactions(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_delete_reaction_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + assert ( + client._transport.delete_message_pin in client._transport._wrapped_methods ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_reaction in client._transport._wrapped_methods - # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_reaction] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_message_pin] = ( + mock_rpc + ) request = {} - client.delete_reaction(request) + client.delete_message_pin(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_reaction(request) + client.delete_message_pin(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_reaction_rest_required_fields( - request_type=reaction.DeleteReactionRequest, +def test_delete_message_pin_rest_required_fields( + request_type=message_pin.DeleteMessagePinRequest, ): transport_class = transports.ChatServiceRestTransport @@ -22893,8 +24712,8 @@ def test_delete_reaction_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseDeleteReaction, - "_BaseDeleteReaction__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseDeleteMessagePin, + "_BaseDeleteMessagePin__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -22942,14 +24761,14 @@ def test_delete_reaction_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_reaction(request) + response = client.delete_message_pin(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_reaction_rest_flattened(): +def test_delete_message_pin_rest_flattened(): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -22961,7 +24780,7 @@ def test_delete_reaction_rest_flattened(): return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"name": "spaces/sample1/messages/sample2/reactions/sample3"} + sample_request = {"name": "spaces/sample1/messagePins/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -22977,19 +24796,18 @@ def test_delete_reaction_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_reaction(**mock_args) + client.delete_message_pin(**mock_args) # Establish that the underlying call 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=spaces/*/messages/*/reactions/*}" % client.transport._host, - args[1], + "%s/v1/{name=spaces/*/messagePins/*}" % client.transport._host, args[1] ) -def test_delete_reaction_rest_flattened_error(transport: str = "rest"): +def test_delete_message_pin_rest_flattened_error(transport: str = "rest"): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -22998,8 +24816,8 @@ def test_delete_reaction_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_reaction( - reaction.DeleteReactionRequest(), + client.delete_message_pin( + message_pin.DeleteMessagePinRequest(), name="name_value", ) @@ -27519,6 +29337,72 @@ def test_delete_reaction_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_message_pins_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_message_pins), "__call__" + ) as call: + call.return_value = message_pin.ListMessagePinsResponse() + client.list_message_pins(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = message_pin.ListMessagePinsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_message_pin_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_message_pin), "__call__" + ) as call: + call.return_value = gc_message_pin.MessagePin() + client.create_message_pin(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_message_pin.CreateMessagePinRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_message_pin_empty_call_grpc(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_message_pin), "__call__" + ) as call: + call.return_value = None + client.delete_message_pin(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = message_pin.DeleteMessagePinRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_create_custom_emoji_empty_call_grpc(): @@ -28795,6 +30679,87 @@ async def test_delete_reaction_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_message_pins_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_message_pins), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + message_pin.ListMessagePinsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_message_pins(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = message_pin.ListMessagePinsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_message_pin_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_message_pin), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_message_pin.MessagePin( + name="name_value", + message="message_value", + ) + ) + await client.create_message_pin(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_message_pin.CreateMessagePinRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_message_pin_empty_call_grpc_asyncio(): + client = ChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_message_pin), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_message_pin(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = message_pin.DeleteMessagePinRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio @@ -29885,6 +31850,7 @@ def test_create_message_rest_call_success(request_type): "principals": [{"audience": {"name": "name_value"}}] }, "join_space_setting": {}, + "view_space_membership_setting": {}, }, }, "customer": "customer_value", @@ -29903,6 +31869,7 @@ def test_create_message_rest_call_success(request_type): "manage_webhooks": {}, "post_messages": {}, "reply_messages": {}, + "view_space_membership": {}, }, "import_mode_expire_time": {}, }, @@ -31124,6 +33091,7 @@ def test_update_message_rest_call_success(request_type): "principals": [{"audience": {"name": "name_value"}}] }, "join_space_setting": {}, + "view_space_membership_setting": {}, }, }, "customer": "customer_value", @@ -31142,6 +33110,7 @@ def test_update_message_rest_call_success(request_type): "manage_webhooks": {}, "post_messages": {}, "reply_messages": {}, + "view_space_membership": {}, }, "import_mode_expire_time": {}, }, @@ -32361,6 +34330,7 @@ def test_create_space_rest_call_success(request_type): "principals": [{"audience": {"name": "name_value"}}] }, "join_space_setting": {}, + "view_space_membership_setting": {}, }, }, "customer": "customer_value", @@ -32379,6 +34349,7 @@ def test_create_space_rest_call_success(request_type): "manage_webhooks": {}, "post_messages": {}, "reply_messages": {}, + "view_space_membership": {}, }, "import_mode_expire_time": {}, } @@ -32658,7 +34629,512 @@ def test_set_up_space_rest_call_success(request_type): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_up_space_rest_interceptors(null_interceptor): +def test_set_up_space_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.ChatServiceRestInterceptor, "post_set_up_space" + ) as post, + mock.patch.object( + transports.ChatServiceRestInterceptor, "post_set_up_space_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_set_up_space" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = space_setup.SetUpSpaceRequest.pb(space_setup.SetUpSpaceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = space.Space.to_json(space.Space()) + req.return_value.content = return_value + + request = space_setup.SetUpSpaceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = space.Space() + post_with_metadata.return_value = space.Space(), metadata + + client.set_up_space( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_space_rest_bad_request(request_type=gc_space.UpdateSpaceRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"space": {"name": "spaces/sample1"}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_space(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gc_space.UpdateSpaceRequest, + dict, + ], +) +def test_update_space_rest_call_success(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"space": {"name": "spaces/sample1"}} + request_init["space"] = { + "name": "spaces/sample1", + "type_": 1, + "space_type": 1, + "single_user_bot_dm": True, + "threaded": True, + "display_name": "display_name_value", + "external_user_allowed": True, + "space_threading_state": 2, + "space_details": { + "description": "description_value", + "guidelines": "guidelines_value", + }, + "space_history_state": 1, + "import_mode": True, + "create_time": {"seconds": 751, "nanos": 543}, + "last_active_time": {}, + "admin_installed": True, + "membership_count": { + "joined_direct_human_user_count": 3185, + "joined_group_count": 1933, + }, + "access_settings": { + "access_state": 1, + "audience": "audience_value", + "access_permission_settings": { + "discover_space_setting": { + "principals": [{"audience": {"name": "name_value"}}] + }, + "join_space_setting": {}, + "view_space_membership_setting": {}, + }, + }, + "customer": "customer_value", + "space_uri": "space_uri_value", + "predefined_permission_settings": 1, + "permission_settings": { + "manage_members_and_groups": { + "managers_allowed": True, + "assistant_managers_allowed": True, + "members_allowed": True, + }, + "modify_space_details": {}, + "toggle_history": {}, + "use_at_mention_all": {}, + "manage_apps": {}, + "manage_webhooks": {}, + "post_messages": {}, + "reply_messages": {}, + "view_space_membership": {}, + }, + "import_mode_expire_time": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gc_space.UpdateSpaceRequest.meta.fields["space"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["space"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["space"][field])): + del request_init["space"][field][i][subfield] + else: + del request_init["space"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gc_space.Space( + name="name_value", + type_=gc_space.Space.Type.ROOM, + space_type=gc_space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + customer="customer_value", + space_uri="space_uri_value", + predefined_permission_settings=gc_space.Space.PredefinedPermissionSettings.COLLABORATION_SPACE, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gc_space.Space.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_space(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_space.Space) + assert response.name == "name_value" + assert response.type_ == gc_space.Space.Type.ROOM + assert response.space_type == gc_space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == gc_space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + assert response.customer == "customer_value" + assert response.space_uri == "space_uri_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_space_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.ChatServiceRestInterceptor, "post_update_space" + ) as post, + mock.patch.object( + transports.ChatServiceRestInterceptor, "post_update_space_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_update_space" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gc_space.UpdateSpaceRequest.pb(gc_space.UpdateSpaceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gc_space.Space.to_json(gc_space.Space()) + req.return_value.content = return_value + + request = gc_space.UpdateSpaceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gc_space.Space() + post_with_metadata.return_value = gc_space.Space(), metadata + + client.update_space( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_space_rest_bad_request(request_type=space.DeleteSpaceRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_space(request) + + +@pytest.mark.parametrize( + "request_type", + [ + space.DeleteSpaceRequest, + dict, + ], +) +def test_delete_space_rest_call_success(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_space(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_space_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_delete_space" + ) as pre, + ): + pre.assert_not_called() + pb_message = space.DeleteSpaceRequest.pb(space.DeleteSpaceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = space.DeleteSpaceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_space( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_complete_import_space_rest_bad_request( + request_type=space.CompleteImportSpaceRequest, +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.complete_import_space(request) + + +@pytest.mark.parametrize( + "request_type", + [ + space.CompleteImportSpaceRequest, + dict, + ], +) +def test_complete_import_space_rest_call_success(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = space.CompleteImportSpaceResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = space.CompleteImportSpaceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.complete_import_space(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, space.CompleteImportSpaceResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_complete_import_space_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -32671,19 +35147,22 @@ def test_set_up_space_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_set_up_space" + transports.ChatServiceRestInterceptor, "post_complete_import_space" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_set_up_space_with_metadata" + transports.ChatServiceRestInterceptor, + "post_complete_import_space_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_set_up_space" + transports.ChatServiceRestInterceptor, "pre_complete_import_space" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = space_setup.SetUpSpaceRequest.pb(space_setup.SetUpSpaceRequest()) + pb_message = space.CompleteImportSpaceRequest.pb( + space.CompleteImportSpaceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -32694,19 +35173,21 @@ def test_set_up_space_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = space.Space.to_json(space.Space()) + return_value = space.CompleteImportSpaceResponse.to_json( + space.CompleteImportSpaceResponse() + ) req.return_value.content = return_value - request = space_setup.SetUpSpaceRequest() + request = space.CompleteImportSpaceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = space.Space() - post_with_metadata.return_value = space.Space(), metadata + post.return_value = space.CompleteImportSpaceResponse() + post_with_metadata.return_value = space.CompleteImportSpaceResponse(), metadata - client.set_up_space( + client.complete_import_space( request, metadata=[ ("key", "val"), @@ -32719,12 +35200,14 @@ def test_set_up_space_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_space_rest_bad_request(request_type=gc_space.UpdateSpaceRequest): +def test_find_direct_message_rest_bad_request( + request_type=space.FindDirectMessageRequest, +): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"space": {"name": "spaces/sample1"}} + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -32740,161 +35223,43 @@ def test_update_space_rest_bad_request(request_type=gc_space.UpdateSpaceRequest) response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_space(request) + client.find_direct_message(request) @pytest.mark.parametrize( "request_type", [ - gc_space.UpdateSpaceRequest, + space.FindDirectMessageRequest, dict, ], ) -def test_update_space_rest_call_success(request_type): +def test_find_direct_message_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"space": {"name": "spaces/sample1"}} - request_init["space"] = { - "name": "spaces/sample1", - "type_": 1, - "space_type": 1, - "single_user_bot_dm": True, - "threaded": True, - "display_name": "display_name_value", - "external_user_allowed": True, - "space_threading_state": 2, - "space_details": { - "description": "description_value", - "guidelines": "guidelines_value", - }, - "space_history_state": 1, - "import_mode": True, - "create_time": {"seconds": 751, "nanos": 543}, - "last_active_time": {}, - "admin_installed": True, - "membership_count": { - "joined_direct_human_user_count": 3185, - "joined_group_count": 1933, - }, - "access_settings": { - "access_state": 1, - "audience": "audience_value", - "access_permission_settings": { - "discover_space_setting": { - "principals": [{"audience": {"name": "name_value"}}] - }, - "join_space_setting": {}, - }, - }, - "customer": "customer_value", - "space_uri": "space_uri_value", - "predefined_permission_settings": 1, - "permission_settings": { - "manage_members_and_groups": { - "managers_allowed": True, - "assistant_managers_allowed": True, - "members_allowed": True, - }, - "modify_space_details": {}, - "toggle_history": {}, - "use_at_mention_all": {}, - "manage_apps": {}, - "manage_webhooks": {}, - "post_messages": {}, - "reply_messages": {}, - }, - "import_mode_expire_time": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = gc_space.UpdateSpaceRequest.meta.fields["space"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["space"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["space"][field])): - del request_init["space"][field][i][subfield] - else: - del request_init["space"][field][subfield] + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gc_space.Space( + return_value = space.Space( name="name_value", - type_=gc_space.Space.Type.ROOM, - space_type=gc_space.Space.SpaceType.SPACE, + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, single_user_bot_dm=True, threaded=True, display_name="display_name_value", external_user_allowed=True, - space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, space_history_state=history_state.HistoryState.HISTORY_OFF, import_mode=True, admin_installed=True, customer="customer_value", space_uri="space_uri_value", - predefined_permission_settings=gc_space.Space.PredefinedPermissionSettings.COLLABORATION_SPACE, + predefined_permission_settings=space.Space.PredefinedPermissionSettings.COLLABORATION_SPACE, ) # Wrap the value into a proper Response obj @@ -32902,25 +35267,25 @@ def get_message_fields(field): response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_space.Space.pb(return_value) + return_value = space.Space.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_space(request) + response = client.find_direct_message(request) # Establish that the response is the type that we expect. - assert isinstance(response, gc_space.Space) + assert isinstance(response, space.Space) assert response.name == "name_value" - assert response.type_ == gc_space.Space.Type.ROOM - assert response.space_type == gc_space.Space.SpaceType.SPACE + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE assert response.single_user_bot_dm is True assert response.threaded is True assert response.display_name == "display_name_value" assert response.external_user_allowed is True assert ( response.space_threading_state - == gc_space.Space.SpaceThreadingState.THREADED_MESSAGES + == space.Space.SpaceThreadingState.THREADED_MESSAGES ) assert response.space_history_state == history_state.HistoryState.HISTORY_OFF assert response.import_mode is True @@ -32930,7 +35295,7 @@ def get_message_fields(field): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_space_rest_interceptors(null_interceptor): +def test_find_direct_message_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -32943,19 +35308,20 @@ def test_update_space_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_update_space" + transports.ChatServiceRestInterceptor, "post_find_direct_message" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_update_space_with_metadata" + transports.ChatServiceRestInterceptor, + "post_find_direct_message_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_update_space" + transports.ChatServiceRestInterceptor, "pre_find_direct_message" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gc_space.UpdateSpaceRequest.pb(gc_space.UpdateSpaceRequest()) + pb_message = space.FindDirectMessageRequest.pb(space.FindDirectMessageRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -32966,19 +35332,19 @@ def test_update_space_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = gc_space.Space.to_json(gc_space.Space()) + return_value = space.Space.to_json(space.Space()) req.return_value.content = return_value - request = gc_space.UpdateSpaceRequest() + request = space.FindDirectMessageRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gc_space.Space() - post_with_metadata.return_value = gc_space.Space(), metadata + post.return_value = space.Space() + post_with_metadata.return_value = space.Space(), metadata - client.update_space( + client.find_direct_message( request, metadata=[ ("key", "val"), @@ -32991,12 +35357,12 @@ def test_update_space_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_space_rest_bad_request(request_type=space.DeleteSpaceRequest): +def test_find_group_chats_rest_bad_request(request_type=space.FindGroupChatsRequest): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1"} + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -33012,45 +35378,51 @@ def test_delete_space_rest_bad_request(request_type=space.DeleteSpaceRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_space(request) + client.find_group_chats(request) @pytest.mark.parametrize( "request_type", [ - space.DeleteSpaceRequest, + space.FindGroupChatsRequest, dict, ], ) -def test_delete_space_rest_call_success(request_type): +def test_find_group_chats_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1"} + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = space.FindGroupChatsResponse( + next_page_token="next_page_token_value", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = space.FindGroupChatsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_space(request) + response = client.find_group_chats(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, pagers.FindGroupChatsPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_space_rest_interceptors(null_interceptor): +def test_find_group_chats_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -33063,11 +35435,19 @@ def test_delete_space_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_delete_space" + transports.ChatServiceRestInterceptor, "post_find_group_chats" + ) as post, + mock.patch.object( + transports.ChatServiceRestInterceptor, "post_find_group_chats_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_find_group_chats" ) as pre, ): pre.assert_not_called() - pb_message = space.DeleteSpaceRequest.pb(space.DeleteSpaceRequest()) + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = space.FindGroupChatsRequest.pb(space.FindGroupChatsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -33078,15 +35458,21 @@ def test_delete_space_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = space.FindGroupChatsResponse.to_json( + space.FindGroupChatsResponse() + ) + req.return_value.content = return_value - request = space.DeleteSpaceRequest() + request = space.FindGroupChatsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = space.FindGroupChatsResponse() + post_with_metadata.return_value = space.FindGroupChatsResponse(), metadata - client.delete_space( + client.find_group_chats( request, metadata=[ ("key", "val"), @@ -33095,16 +35481,18 @@ def test_delete_space_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_complete_import_space_rest_bad_request( - request_type=space.CompleteImportSpaceRequest, +def test_create_membership_rest_bad_request( + request_type=gc_membership.CreateMembershipRequest, ): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1"} + request_init = {"parent": "spaces/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -33120,48 +35508,140 @@ def test_complete_import_space_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.complete_import_space(request) + client.create_membership(request) @pytest.mark.parametrize( "request_type", [ - space.CompleteImportSpaceRequest, + gc_membership.CreateMembershipRequest, dict, ], ) -def test_complete_import_space_rest_call_success(request_type): +def test_create_membership_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1"} + request_init = {"parent": "spaces/sample1"} + request_init["membership"] = { + "name": "name_value", + "state": 1, + "role": 1, + "member": { + "name": "name_value", + "display_name": "display_name_value", + "domain_id": "domain_id_value", + "type_": 1, + "is_anonymous": True, + }, + "group_member": {"name": "name_value"}, + "create_time": {"seconds": 751, "nanos": 543}, + "delete_time": {}, + "affiliation": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gc_membership.CreateMembershipRequest.meta.fields["membership"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["membership"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["membership"][field])): + del request_init["membership"][field][i][subfield] + else: + del request_init["membership"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = space.CompleteImportSpaceResponse() + return_value = gc_membership.Membership( + name="name_value", + state=gc_membership.Membership.MembershipState.JOINED, + role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, + affiliation=gc_membership.Membership.Affiliation.INTERNAL, + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 # Convert return value to protobuf type - return_value = space.CompleteImportSpaceResponse.pb(return_value) + return_value = gc_membership.Membership.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.complete_import_space(request) + response = client.create_membership(request) # Establish that the response is the type that we expect. - assert isinstance(response, space.CompleteImportSpaceResponse) + assert isinstance(response, gc_membership.Membership) + assert response.name == "name_value" + assert response.state == gc_membership.Membership.MembershipState.JOINED + assert response.role == gc_membership.Membership.MembershipRole.ROLE_MEMBER + assert response.affiliation == gc_membership.Membership.Affiliation.INTERNAL @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_complete_import_space_rest_interceptors(null_interceptor): +def test_create_membership_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -33174,21 +35654,21 @@ def test_complete_import_space_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_complete_import_space" + transports.ChatServiceRestInterceptor, "post_create_membership" ) as post, mock.patch.object( transports.ChatServiceRestInterceptor, - "post_complete_import_space_with_metadata", + "post_create_membership_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_complete_import_space" + transports.ChatServiceRestInterceptor, "pre_create_membership" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = space.CompleteImportSpaceRequest.pb( - space.CompleteImportSpaceRequest() + pb_message = gc_membership.CreateMembershipRequest.pb( + gc_membership.CreateMembershipRequest() ) transcode.return_value = { "method": "post", @@ -33200,21 +35680,19 @@ def test_complete_import_space_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = space.CompleteImportSpaceResponse.to_json( - space.CompleteImportSpaceResponse() - ) + return_value = gc_membership.Membership.to_json(gc_membership.Membership()) req.return_value.content = return_value - request = space.CompleteImportSpaceRequest() + request = gc_membership.CreateMembershipRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = space.CompleteImportSpaceResponse() - post_with_metadata.return_value = space.CompleteImportSpaceResponse(), metadata + post.return_value = gc_membership.Membership() + post_with_metadata.return_value = gc_membership.Membership(), metadata - client.complete_import_space( + client.create_membership( request, metadata=[ ("key", "val"), @@ -33227,14 +35705,14 @@ def test_complete_import_space_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_find_direct_message_rest_bad_request( - request_type=space.FindDirectMessageRequest, +def test_update_membership_rest_bad_request( + request_type=gc_membership.UpdateMembershipRequest, ): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"membership": {"name": "spaces/sample1/members/sample2"}} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -33250,43 +35728,116 @@ def test_find_direct_message_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.find_direct_message(request) + client.update_membership(request) @pytest.mark.parametrize( "request_type", [ - space.FindDirectMessageRequest, + gc_membership.UpdateMembershipRequest, dict, ], ) -def test_find_direct_message_rest_call_success(request_type): +def test_update_membership_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"membership": {"name": "spaces/sample1/members/sample2"}} + request_init["membership"] = { + "name": "spaces/sample1/members/sample2", + "state": 1, + "role": 1, + "member": { + "name": "name_value", + "display_name": "display_name_value", + "domain_id": "domain_id_value", + "type_": 1, + "is_anonymous": True, + }, + "group_member": {"name": "name_value"}, + "create_time": {"seconds": 751, "nanos": 543}, + "delete_time": {}, + "affiliation": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gc_membership.UpdateMembershipRequest.meta.fields["membership"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["membership"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["membership"][field])): + del request_init["membership"][field][i][subfield] + else: + del request_init["membership"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = space.Space( - name="name_value", - type_=space.Space.Type.ROOM, - space_type=space.Space.SpaceType.SPACE, - single_user_bot_dm=True, - threaded=True, - display_name="display_name_value", - external_user_allowed=True, - space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, - space_history_state=history_state.HistoryState.HISTORY_OFF, - import_mode=True, - admin_installed=True, - customer="customer_value", - space_uri="space_uri_value", - predefined_permission_settings=space.Space.PredefinedPermissionSettings.COLLABORATION_SPACE, + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gc_membership.Membership( + name="name_value", + state=gc_membership.Membership.MembershipState.JOINED, + role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, + affiliation=gc_membership.Membership.Affiliation.INTERNAL, ) # Wrap the value into a proper Response obj @@ -33294,35 +35845,23 @@ def test_find_direct_message_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = space.Space.pb(return_value) + return_value = gc_membership.Membership.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.find_direct_message(request) + response = client.update_membership(request) # Establish that the response is the type that we expect. - assert isinstance(response, space.Space) + assert isinstance(response, gc_membership.Membership) assert response.name == "name_value" - assert response.type_ == space.Space.Type.ROOM - assert response.space_type == space.Space.SpaceType.SPACE - assert response.single_user_bot_dm is True - assert response.threaded is True - assert response.display_name == "display_name_value" - assert response.external_user_allowed is True - assert ( - response.space_threading_state - == space.Space.SpaceThreadingState.THREADED_MESSAGES - ) - assert response.space_history_state == history_state.HistoryState.HISTORY_OFF - assert response.import_mode is True - assert response.admin_installed is True - assert response.customer == "customer_value" - assert response.space_uri == "space_uri_value" + assert response.state == gc_membership.Membership.MembershipState.JOINED + assert response.role == gc_membership.Membership.MembershipRole.ROLE_MEMBER + assert response.affiliation == gc_membership.Membership.Affiliation.INTERNAL @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_find_direct_message_rest_interceptors(null_interceptor): +def test_update_membership_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -33335,20 +35874,22 @@ def test_find_direct_message_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_find_direct_message" + transports.ChatServiceRestInterceptor, "post_update_membership" ) as post, mock.patch.object( transports.ChatServiceRestInterceptor, - "post_find_direct_message_with_metadata", + "post_update_membership_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_find_direct_message" + transports.ChatServiceRestInterceptor, "pre_update_membership" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = space.FindDirectMessageRequest.pb(space.FindDirectMessageRequest()) + pb_message = gc_membership.UpdateMembershipRequest.pb( + gc_membership.UpdateMembershipRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -33359,19 +35900,19 @@ def test_find_direct_message_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = space.Space.to_json(space.Space()) + return_value = gc_membership.Membership.to_json(gc_membership.Membership()) req.return_value.content = return_value - request = space.FindDirectMessageRequest() + request = gc_membership.UpdateMembershipRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = space.Space() - post_with_metadata.return_value = space.Space(), metadata + post.return_value = gc_membership.Membership() + post_with_metadata.return_value = gc_membership.Membership(), metadata - client.find_direct_message( + client.update_membership( request, metadata=[ ("key", "val"), @@ -33384,12 +35925,14 @@ def test_find_direct_message_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_find_group_chats_rest_bad_request(request_type=space.FindGroupChatsRequest): +def test_delete_membership_rest_bad_request( + request_type=membership.DeleteMembershipRequest, +): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"name": "spaces/sample1/members/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -33405,30 +35948,33 @@ def test_find_group_chats_rest_bad_request(request_type=space.FindGroupChatsRequ response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.find_group_chats(request) + client.delete_membership(request) @pytest.mark.parametrize( "request_type", [ - space.FindGroupChatsRequest, + membership.DeleteMembershipRequest, dict, ], ) -def test_find_group_chats_rest_call_success(request_type): +def test_delete_membership_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"name": "spaces/sample1/members/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 = space.FindGroupChatsResponse( - next_page_token="next_page_token_value", + return_value = membership.Membership( + name="name_value", + state=membership.Membership.MembershipState.JOINED, + role=membership.Membership.MembershipRole.ROLE_MEMBER, + affiliation=membership.Membership.Affiliation.INTERNAL, ) # Wrap the value into a proper Response obj @@ -33436,20 +35982,23 @@ def test_find_group_chats_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = space.FindGroupChatsResponse.pb(return_value) + return_value = membership.Membership.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.find_group_chats(request) + response = client.delete_membership(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FindGroupChatsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, membership.Membership) + assert response.name == "name_value" + assert response.state == membership.Membership.MembershipState.JOINED + assert response.role == membership.Membership.MembershipRole.ROLE_MEMBER + assert response.affiliation == membership.Membership.Affiliation.INTERNAL @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_find_group_chats_rest_interceptors(null_interceptor): +def test_delete_membership_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -33462,19 +36011,22 @@ def test_find_group_chats_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_find_group_chats" + transports.ChatServiceRestInterceptor, "post_delete_membership" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_find_group_chats_with_metadata" + transports.ChatServiceRestInterceptor, + "post_delete_membership_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_find_group_chats" + transports.ChatServiceRestInterceptor, "pre_delete_membership" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = space.FindGroupChatsRequest.pb(space.FindGroupChatsRequest()) + pb_message = membership.DeleteMembershipRequest.pb( + membership.DeleteMembershipRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -33485,21 +36037,19 @@ def test_find_group_chats_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = space.FindGroupChatsResponse.to_json( - space.FindGroupChatsResponse() - ) + return_value = membership.Membership.to_json(membership.Membership()) req.return_value.content = return_value - request = space.FindGroupChatsRequest() + request = membership.DeleteMembershipRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = space.FindGroupChatsResponse() - post_with_metadata.return_value = space.FindGroupChatsResponse(), metadata + post.return_value = membership.Membership() + post_with_metadata.return_value = membership.Membership(), metadata - client.find_group_chats( + client.delete_membership( request, metadata=[ ("key", "val"), @@ -33512,14 +36062,14 @@ def test_find_group_chats_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_membership_rest_bad_request( - request_type=gc_membership.CreateMembershipRequest, +def test_create_reaction_rest_bad_request( + request_type=gc_reaction.CreateReactionRequest, ): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1"} + request_init = {"parent": "spaces/sample1/messages/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -33535,45 +36085,52 @@ def test_create_membership_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_membership(request) + client.create_reaction(request) @pytest.mark.parametrize( "request_type", [ - gc_membership.CreateMembershipRequest, + gc_reaction.CreateReactionRequest, dict, ], ) -def test_create_membership_rest_call_success(request_type): +def test_create_reaction_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1"} - request_init["membership"] = { + request_init = {"parent": "spaces/sample1/messages/sample2"} + request_init["reaction"] = { "name": "name_value", - "state": 1, - "role": 1, - "member": { + "user": { "name": "name_value", "display_name": "display_name_value", "domain_id": "domain_id_value", "type_": 1, "is_anonymous": True, }, - "group_member": {"name": "name_value"}, - "create_time": {"seconds": 751, "nanos": 543}, - "delete_time": {}, - "affiliation": 1, + "emoji": { + "unicode": "unicode_value", + "custom_emoji": { + "name": "name_value", + "uid": "uid_value", + "emoji_name": "emoji_name_value", + "temporary_image_uri": "temporary_image_uri_value", + "payload": { + "file_content": b"file_content_blob", + "filename": "filename_value", + }, + }, + }, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = gc_membership.CreateMembershipRequest.meta.fields["membership"] + test_field = gc_reaction.CreateReactionRequest.meta.fields["reaction"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -33601,7 +36158,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["membership"].items(): # pragma: NO COVER + for field, value in request_init["reaction"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -33631,20 +36188,17 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["membership"][field])): - del request_init["membership"][field][i][subfield] + for i in range(0, len(request_init["reaction"][field])): + del request_init["reaction"][field][i][subfield] else: - del request_init["membership"][field][subfield] + del request_init["reaction"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gc_membership.Membership( + return_value = gc_reaction.Reaction( name="name_value", - state=gc_membership.Membership.MembershipState.JOINED, - role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, - affiliation=gc_membership.Membership.Affiliation.INTERNAL, ) # Wrap the value into a proper Response obj @@ -33652,23 +36206,20 @@ def get_message_fields(field): response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_membership.Membership.pb(return_value) + return_value = gc_reaction.Reaction.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_membership(request) + response = client.create_reaction(request) # Establish that the response is the type that we expect. - assert isinstance(response, gc_membership.Membership) + assert isinstance(response, gc_reaction.Reaction) assert response.name == "name_value" - assert response.state == gc_membership.Membership.MembershipState.JOINED - assert response.role == gc_membership.Membership.MembershipRole.ROLE_MEMBER - assert response.affiliation == gc_membership.Membership.Affiliation.INTERNAL @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_membership_rest_interceptors(null_interceptor): +def test_create_reaction_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -33681,21 +36232,20 @@ def test_create_membership_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_create_membership" + transports.ChatServiceRestInterceptor, "post_create_reaction" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, - "post_create_membership_with_metadata", + transports.ChatServiceRestInterceptor, "post_create_reaction_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_create_membership" + transports.ChatServiceRestInterceptor, "pre_create_reaction" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gc_membership.CreateMembershipRequest.pb( - gc_membership.CreateMembershipRequest() + pb_message = gc_reaction.CreateReactionRequest.pb( + gc_reaction.CreateReactionRequest() ) transcode.return_value = { "method": "post", @@ -33707,19 +36257,19 @@ def test_create_membership_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = gc_membership.Membership.to_json(gc_membership.Membership()) + return_value = gc_reaction.Reaction.to_json(gc_reaction.Reaction()) req.return_value.content = return_value - request = gc_membership.CreateMembershipRequest() + request = gc_reaction.CreateReactionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gc_membership.Membership() - post_with_metadata.return_value = gc_membership.Membership(), metadata + post.return_value = gc_reaction.Reaction() + post_with_metadata.return_value = gc_reaction.Reaction(), metadata - client.create_membership( + client.create_reaction( request, metadata=[ ("key", "val"), @@ -33732,14 +36282,12 @@ def test_create_membership_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_membership_rest_bad_request( - request_type=gc_membership.UpdateMembershipRequest, -): +def test_list_reactions_rest_bad_request(request_type=reaction.ListReactionsRequest): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"membership": {"name": "spaces/sample1/members/sample2"}} + request_init = {"parent": "spaces/sample1/messages/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -33755,116 +36303,30 @@ def test_update_membership_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_membership(request) + client.list_reactions(request) @pytest.mark.parametrize( "request_type", [ - gc_membership.UpdateMembershipRequest, + reaction.ListReactionsRequest, dict, ], ) -def test_update_membership_rest_call_success(request_type): +def test_list_reactions_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"membership": {"name": "spaces/sample1/members/sample2"}} - request_init["membership"] = { - "name": "spaces/sample1/members/sample2", - "state": 1, - "role": 1, - "member": { - "name": "name_value", - "display_name": "display_name_value", - "domain_id": "domain_id_value", - "type_": 1, - "is_anonymous": True, - }, - "group_member": {"name": "name_value"}, - "create_time": {"seconds": 751, "nanos": 543}, - "delete_time": {}, - "affiliation": 1, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = gc_membership.UpdateMembershipRequest.meta.fields["membership"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["membership"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["membership"][field])): - del request_init["membership"][field][i][subfield] - else: - del request_init["membership"][field][subfield] + request_init = {"parent": "spaces/sample1/messages/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 = gc_membership.Membership( - name="name_value", - state=gc_membership.Membership.MembershipState.JOINED, - role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, - affiliation=gc_membership.Membership.Affiliation.INTERNAL, + return_value = reaction.ListReactionsResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -33872,23 +36334,20 @@ def get_message_fields(field): response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_membership.Membership.pb(return_value) + return_value = reaction.ListReactionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_membership(request) + response = client.list_reactions(request) # Establish that the response is the type that we expect. - assert isinstance(response, gc_membership.Membership) - assert response.name == "name_value" - assert response.state == gc_membership.Membership.MembershipState.JOINED - assert response.role == gc_membership.Membership.MembershipRole.ROLE_MEMBER - assert response.affiliation == gc_membership.Membership.Affiliation.INTERNAL + assert isinstance(response, pagers.ListReactionsPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_membership_rest_interceptors(null_interceptor): +def test_list_reactions_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -33901,22 +36360,19 @@ def test_update_membership_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_update_membership" + transports.ChatServiceRestInterceptor, "post_list_reactions" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, - "post_update_membership_with_metadata", + transports.ChatServiceRestInterceptor, "post_list_reactions_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_update_membership" + transports.ChatServiceRestInterceptor, "pre_list_reactions" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gc_membership.UpdateMembershipRequest.pb( - gc_membership.UpdateMembershipRequest() - ) + pb_message = reaction.ListReactionsRequest.pb(reaction.ListReactionsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -33927,19 +36383,21 @@ def test_update_membership_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = gc_membership.Membership.to_json(gc_membership.Membership()) + return_value = reaction.ListReactionsResponse.to_json( + reaction.ListReactionsResponse() + ) req.return_value.content = return_value - request = gc_membership.UpdateMembershipRequest() + request = reaction.ListReactionsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gc_membership.Membership() - post_with_metadata.return_value = gc_membership.Membership(), metadata + post.return_value = reaction.ListReactionsResponse() + post_with_metadata.return_value = reaction.ListReactionsResponse(), metadata - client.update_membership( + client.list_reactions( request, metadata=[ ("key", "val"), @@ -33952,14 +36410,120 @@ def test_update_membership_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_membership_rest_bad_request( - request_type=membership.DeleteMembershipRequest, +def test_delete_reaction_rest_bad_request(request_type=reaction.DeleteReactionRequest): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/messages/sample2/reactions/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_reaction(request) + + +@pytest.mark.parametrize( + "request_type", + [ + reaction.DeleteReactionRequest, + dict, + ], +) +def test_delete_reaction_rest_call_success(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/messages/sample2/reactions/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 = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_reaction(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_reaction_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_delete_reaction" + ) as pre, + ): + pre.assert_not_called() + pb_message = reaction.DeleteReactionRequest.pb(reaction.DeleteReactionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = reaction.DeleteReactionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_reaction( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_list_message_pins_rest_bad_request( + request_type=message_pin.ListMessagePinsRequest, ): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1/members/sample2"} + request_init = {"parent": "spaces/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -33975,33 +36539,30 @@ def test_delete_membership_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_membership(request) + client.list_message_pins(request) @pytest.mark.parametrize( "request_type", [ - membership.DeleteMembershipRequest, + message_pin.ListMessagePinsRequest, dict, ], ) -def test_delete_membership_rest_call_success(request_type): +def test_list_message_pins_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1/members/sample2"} + request_init = {"parent": "spaces/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = membership.Membership( - name="name_value", - state=membership.Membership.MembershipState.JOINED, - role=membership.Membership.MembershipRole.ROLE_MEMBER, - affiliation=membership.Membership.Affiliation.INTERNAL, + return_value = message_pin.ListMessagePinsResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -34009,23 +36570,20 @@ def test_delete_membership_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = membership.Membership.pb(return_value) + return_value = message_pin.ListMessagePinsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_membership(request) + response = client.list_message_pins(request) # Establish that the response is the type that we expect. - assert isinstance(response, membership.Membership) - assert response.name == "name_value" - assert response.state == membership.Membership.MembershipState.JOINED - assert response.role == membership.Membership.MembershipRole.ROLE_MEMBER - assert response.affiliation == membership.Membership.Affiliation.INTERNAL + assert isinstance(response, pagers.ListMessagePinsPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_membership_rest_interceptors(null_interceptor): +def test_list_message_pins_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -34038,21 +36596,21 @@ def test_delete_membership_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_delete_membership" + transports.ChatServiceRestInterceptor, "post_list_message_pins" ) as post, mock.patch.object( transports.ChatServiceRestInterceptor, - "post_delete_membership_with_metadata", + "post_list_message_pins_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_delete_membership" + transports.ChatServiceRestInterceptor, "pre_list_message_pins" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = membership.DeleteMembershipRequest.pb( - membership.DeleteMembershipRequest() + pb_message = message_pin.ListMessagePinsRequest.pb( + message_pin.ListMessagePinsRequest() ) transcode.return_value = { "method": "post", @@ -34064,19 +36622,24 @@ def test_delete_membership_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = membership.Membership.to_json(membership.Membership()) + return_value = message_pin.ListMessagePinsResponse.to_json( + message_pin.ListMessagePinsResponse() + ) req.return_value.content = return_value - request = membership.DeleteMembershipRequest() + request = message_pin.ListMessagePinsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = membership.Membership() - post_with_metadata.return_value = membership.Membership(), metadata + post.return_value = message_pin.ListMessagePinsResponse() + post_with_metadata.return_value = ( + message_pin.ListMessagePinsResponse(), + metadata, + ) - client.delete_membership( + client.list_message_pins( request, metadata=[ ("key", "val"), @@ -34089,14 +36652,14 @@ def test_delete_membership_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_reaction_rest_bad_request( - request_type=gc_reaction.CreateReactionRequest, +def test_create_message_pin_rest_bad_request( + request_type=gc_message_pin.CreateMessagePinRequest, ): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1/messages/sample2"} + request_init = {"parent": "spaces/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -34112,52 +36675,30 @@ def test_create_reaction_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_reaction(request) + client.create_message_pin(request) @pytest.mark.parametrize( "request_type", [ - gc_reaction.CreateReactionRequest, + gc_message_pin.CreateMessagePinRequest, dict, ], ) -def test_create_reaction_rest_call_success(request_type): +def test_create_message_pin_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1/messages/sample2"} - request_init["reaction"] = { - "name": "name_value", - "user": { - "name": "name_value", - "display_name": "display_name_value", - "domain_id": "domain_id_value", - "type_": 1, - "is_anonymous": True, - }, - "emoji": { - "unicode": "unicode_value", - "custom_emoji": { - "name": "name_value", - "uid": "uid_value", - "emoji_name": "emoji_name_value", - "temporary_image_uri": "temporary_image_uri_value", - "payload": { - "file_content": b"file_content_blob", - "filename": "filename_value", - }, - }, - }, - } + request_init = {"parent": "spaces/sample1"} + request_init["message_pin"] = {"name": "name_value", "message": "message_value"} # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = gc_reaction.CreateReactionRequest.meta.fields["reaction"] + test_field = gc_message_pin.CreateMessagePinRequest.meta.fields["message_pin"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -34185,7 +36726,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["reaction"].items(): # pragma: NO COVER + for field, value in request_init["message_pin"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -34215,17 +36756,18 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["reaction"][field])): - del request_init["reaction"][field][i][subfield] + for i in range(0, len(request_init["message_pin"][field])): + del request_init["message_pin"][field][i][subfield] else: - del request_init["reaction"][field][subfield] + del request_init["message_pin"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gc_reaction.Reaction( + return_value = gc_message_pin.MessagePin( name="name_value", + message="message_value", ) # Wrap the value into a proper Response obj @@ -34233,20 +36775,21 @@ def get_message_fields(field): response_value.status_code = 200 # Convert return value to protobuf type - return_value = gc_reaction.Reaction.pb(return_value) + return_value = gc_message_pin.MessagePin.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_reaction(request) + response = client.create_message_pin(request) # Establish that the response is the type that we expect. - assert isinstance(response, gc_reaction.Reaction) + assert isinstance(response, gc_message_pin.MessagePin) assert response.name == "name_value" + assert response.message == "message_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_reaction_rest_interceptors(null_interceptor): +def test_create_message_pin_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -34259,20 +36802,21 @@ def test_create_reaction_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_create_reaction" + transports.ChatServiceRestInterceptor, "post_create_message_pin" ) as post, mock.patch.object( - transports.ChatServiceRestInterceptor, "post_create_reaction_with_metadata" + transports.ChatServiceRestInterceptor, + "post_create_message_pin_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_create_reaction" + transports.ChatServiceRestInterceptor, "pre_create_message_pin" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gc_reaction.CreateReactionRequest.pb( - gc_reaction.CreateReactionRequest() + pb_message = gc_message_pin.CreateMessagePinRequest.pb( + gc_message_pin.CreateMessagePinRequest() ) transcode.return_value = { "method": "post", @@ -34284,19 +36828,19 @@ def test_create_reaction_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = gc_reaction.Reaction.to_json(gc_reaction.Reaction()) + return_value = gc_message_pin.MessagePin.to_json(gc_message_pin.MessagePin()) req.return_value.content = return_value - request = gc_reaction.CreateReactionRequest() + request = gc_message_pin.CreateMessagePinRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gc_reaction.Reaction() - post_with_metadata.return_value = gc_reaction.Reaction(), metadata + post.return_value = gc_message_pin.MessagePin() + post_with_metadata.return_value = gc_message_pin.MessagePin(), metadata - client.create_reaction( + client.create_message_pin( request, metadata=[ ("key", "val"), @@ -34309,140 +36853,14 @@ def test_create_reaction_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_reactions_rest_bad_request(request_type=reaction.ListReactionsRequest): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1/messages/sample2"} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_reactions(request) - - -@pytest.mark.parametrize( - "request_type", - [ - reaction.ListReactionsRequest, - dict, - ], -) -def test_list_reactions_rest_call_success(request_type): - client = ChatServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "spaces/sample1/messages/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 = reaction.ListReactionsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = reaction.ListReactionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_reactions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListReactionsPager) - assert response.next_page_token == "next_page_token_value" - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_reactions_rest_interceptors(null_interceptor): - transport = transports.ChatServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ChatServiceRestInterceptor(), - ) - client = ChatServiceClient(transport=transport) - - with ( - mock.patch.object(type(client.transport._session), "request") as req, - mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object( - transports.ChatServiceRestInterceptor, "post_list_reactions" - ) as post, - mock.patch.object( - transports.ChatServiceRestInterceptor, "post_list_reactions_with_metadata" - ) as post_with_metadata, - mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_list_reactions" - ) as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = reaction.ListReactionsRequest.pb(reaction.ListReactionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = reaction.ListReactionsResponse.to_json( - reaction.ListReactionsResponse() - ) - req.return_value.content = return_value - - request = reaction.ListReactionsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = reaction.ListReactionsResponse() - post_with_metadata.return_value = reaction.ListReactionsResponse(), metadata - - client.list_reactions( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_reaction_rest_bad_request(request_type=reaction.DeleteReactionRequest): +def test_delete_message_pin_rest_bad_request( + request_type=message_pin.DeleteMessagePinRequest, +): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1/messages/sample2/reactions/sample3"} + request_init = {"name": "spaces/sample1/messagePins/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -34458,23 +36876,23 @@ def test_delete_reaction_rest_bad_request(request_type=reaction.DeleteReactionRe response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_reaction(request) + client.delete_message_pin(request) @pytest.mark.parametrize( "request_type", [ - reaction.DeleteReactionRequest, + message_pin.DeleteMessagePinRequest, dict, ], ) -def test_delete_reaction_rest_call_success(request_type): +def test_delete_message_pin_rest_call_success(request_type): client = ChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "spaces/sample1/messages/sample2/reactions/sample3"} + request_init = {"name": "spaces/sample1/messagePins/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -34489,14 +36907,14 @@ def test_delete_reaction_rest_call_success(request_type): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_reaction(request) + response = client.delete_message_pin(request) # Establish that the response is the type that we expect. assert response is None @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_reaction_rest_interceptors(null_interceptor): +def test_delete_message_pin_rest_interceptors(null_interceptor): transport = transports.ChatServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -34509,11 +36927,13 @@ def test_delete_reaction_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.ChatServiceRestInterceptor, "pre_delete_reaction" + transports.ChatServiceRestInterceptor, "pre_delete_message_pin" ) as pre, ): pre.assert_not_called() - pb_message = reaction.DeleteReactionRequest.pb(reaction.DeleteReactionRequest()) + pb_message = message_pin.DeleteMessagePinRequest.pb( + message_pin.DeleteMessagePinRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -34525,14 +36945,14 @@ def test_delete_reaction_rest_interceptors(null_interceptor): req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - request = reaction.DeleteReactionRequest() + request = message_pin.DeleteMessagePinRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.delete_reaction( + client.delete_message_pin( request, metadata=[ ("key", "val"), @@ -38560,6 +40980,69 @@ def test_delete_reaction_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_message_pins_empty_call_rest(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_message_pins), "__call__" + ) as call: + client.list_message_pins(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = message_pin.ListMessagePinsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_message_pin_empty_call_rest(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_message_pin), "__call__" + ) as call: + client.create_message_pin(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gc_message_pin.CreateMessagePinRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_message_pin_empty_call_rest(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_message_pin), "__call__" + ) as call: + client.delete_message_pin(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = message_pin.DeleteMessagePinRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_create_custom_emoji_empty_call_rest(): @@ -39084,6 +41567,9 @@ def test_chat_service_base_transport(): "create_reaction", "list_reactions", "delete_reaction", + "list_message_pins", + "create_message_pin", + "delete_message_pin", "create_custom_emoji", "get_custom_emoji", "list_custom_emojis", @@ -39175,6 +41661,8 @@ def test_chat_service_base_transport_with_credentials_file(): "https://www.googleapis.com/auth/chat.messages.readonly", "https://www.googleapis.com/auth/chat.spaces", "https://www.googleapis.com/auth/chat.spaces.create", + "https://www.googleapis.com/auth/chat.spaces.pins", + "https://www.googleapis.com/auth/chat.spaces.pins.readonly", "https://www.googleapis.com/auth/chat.spaces.readonly", "https://www.googleapis.com/auth/chat.users.availability", "https://www.googleapis.com/auth/chat.users.availability.readonly", @@ -39241,6 +41729,8 @@ def test_chat_service_auth_adc(): "https://www.googleapis.com/auth/chat.messages.readonly", "https://www.googleapis.com/auth/chat.spaces", "https://www.googleapis.com/auth/chat.spaces.create", + "https://www.googleapis.com/auth/chat.spaces.pins", + "https://www.googleapis.com/auth/chat.spaces.pins.readonly", "https://www.googleapis.com/auth/chat.spaces.readonly", "https://www.googleapis.com/auth/chat.users.availability", "https://www.googleapis.com/auth/chat.users.availability.readonly", @@ -39301,6 +41791,8 @@ def test_chat_service_transport_auth_adc(transport_class): "https://www.googleapis.com/auth/chat.messages.readonly", "https://www.googleapis.com/auth/chat.spaces", "https://www.googleapis.com/auth/chat.spaces.create", + "https://www.googleapis.com/auth/chat.spaces.pins", + "https://www.googleapis.com/auth/chat.spaces.pins.readonly", "https://www.googleapis.com/auth/chat.spaces.readonly", "https://www.googleapis.com/auth/chat.users.availability", "https://www.googleapis.com/auth/chat.users.availability.readonly", @@ -39394,6 +41886,8 @@ def test_chat_service_transport_create_channel(transport_class, grpc_helpers): "https://www.googleapis.com/auth/chat.messages.readonly", "https://www.googleapis.com/auth/chat.spaces", "https://www.googleapis.com/auth/chat.spaces.create", + "https://www.googleapis.com/auth/chat.spaces.pins", + "https://www.googleapis.com/auth/chat.spaces.pins.readonly", "https://www.googleapis.com/auth/chat.spaces.readonly", "https://www.googleapis.com/auth/chat.users.availability", "https://www.googleapis.com/auth/chat.users.availability.readonly", @@ -39605,6 +42099,15 @@ def test_chat_service_client_transport_session_collision(transport_name): session1 = client1.transport.delete_reaction._session session2 = client2.transport.delete_reaction._session assert session1 != session2 + session1 = client1.transport.list_message_pins._session + session2 = client2.transport.list_message_pins._session + assert session1 != session2 + session1 = client1.transport.create_message_pin._session + session2 = client2.transport.create_message_pin._session + assert session1 != session2 + session1 = client1.transport.delete_message_pin._session + session2 = client2.transport.delete_message_pin._session + assert session1 != session2 session1 = client1.transport.create_custom_emoji._session session2 = client2.transport.create_custom_emoji._session assert session1 != session2 @@ -39907,10 +42410,33 @@ def test_parse_message_path(): assert expected == actual -def test_quoted_message_metadata_path(): +def test_message_pin_path(): space = "cuttlefish" - message = "mussel" - quoted_message_metadata = "winkle" + message_pin = "mussel" + expected = "spaces/{space}/messagePins/{message_pin}".format( + space=space, + message_pin=message_pin, + ) + actual = ChatServiceClient.message_pin_path(space, message_pin) + assert expected == actual + + +def test_parse_message_pin_path(): + expected = { + "space": "winkle", + "message_pin": "nautilus", + } + path = ChatServiceClient.message_pin_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_message_pin_path(path) + assert expected == actual + + +def test_quoted_message_metadata_path(): + space = "scallop" + message = "abalone" + quoted_message_metadata = "squid" expected = "spaces/{space}/messages/{message}/quotedMessageMetadata/{quoted_message_metadata}".format( space=space, message=message, @@ -39924,9 +42450,9 @@ def test_quoted_message_metadata_path(): def test_parse_quoted_message_metadata_path(): expected = { - "space": "nautilus", - "message": "scallop", - "quoted_message_metadata": "abalone", + "space": "clam", + "message": "whelk", + "quoted_message_metadata": "octopus", } path = ChatServiceClient.quoted_message_metadata_path(**expected) @@ -39936,9 +42462,9 @@ def test_parse_quoted_message_metadata_path(): def test_reaction_path(): - space = "squid" - message = "clam" - reaction = "whelk" + space = "oyster" + message = "nudibranch" + reaction = "cuttlefish" expected = "spaces/{space}/messages/{message}/reactions/{reaction}".format( space=space, message=message, @@ -39950,9 +42476,9 @@ def test_reaction_path(): def test_parse_reaction_path(): expected = { - "space": "octopus", - "message": "oyster", - "reaction": "nudibranch", + "space": "mussel", + "message": "winkle", + "reaction": "nautilus", } path = ChatServiceClient.reaction_path(**expected) @@ -39962,8 +42488,8 @@ def test_parse_reaction_path(): def test_section_path(): - user = "cuttlefish" - section = "mussel" + user = "scallop" + section = "abalone" expected = "users/{user}/sections/{section}".format( user=user, section=section, @@ -39974,8 +42500,8 @@ def test_section_path(): def test_parse_section_path(): expected = { - "user": "winkle", - "section": "nautilus", + "user": "squid", + "section": "clam", } path = ChatServiceClient.section_path(**expected) @@ -39985,9 +42511,9 @@ def test_parse_section_path(): def test_section_item_path(): - user = "scallop" - section = "abalone" - item = "squid" + user = "whelk" + section = "octopus" + item = "oyster" expected = "users/{user}/sections/{section}/items/{item}".format( user=user, section=section, @@ -39999,9 +42525,9 @@ def test_section_item_path(): def test_parse_section_item_path(): expected = { - "user": "clam", - "section": "whelk", - "item": "octopus", + "user": "nudibranch", + "section": "cuttlefish", + "item": "mussel", } path = ChatServiceClient.section_item_path(**expected) @@ -40011,7 +42537,7 @@ def test_parse_section_item_path(): def test_space_path(): - space = "oyster" + space = "winkle" expected = "spaces/{space}".format( space=space, ) @@ -40021,7 +42547,7 @@ def test_space_path(): def test_parse_space_path(): expected = { - "space": "nudibranch", + "space": "nautilus", } path = ChatServiceClient.space_path(**expected) @@ -40031,8 +42557,8 @@ def test_parse_space_path(): def test_space_event_path(): - space = "cuttlefish" - space_event = "mussel" + space = "scallop" + space_event = "abalone" expected = "spaces/{space}/spaceEvents/{space_event}".format( space=space, space_event=space_event, @@ -40043,8 +42569,8 @@ def test_space_event_path(): def test_parse_space_event_path(): expected = { - "space": "winkle", - "space_event": "nautilus", + "space": "squid", + "space_event": "clam", } path = ChatServiceClient.space_event_path(**expected) @@ -40054,8 +42580,8 @@ def test_parse_space_event_path(): def test_space_notification_setting_path(): - user = "scallop" - space = "abalone" + user = "whelk" + space = "octopus" expected = "users/{user}/spaces/{space}/spaceNotificationSetting".format( user=user, space=space, @@ -40066,8 +42592,8 @@ def test_space_notification_setting_path(): def test_parse_space_notification_setting_path(): expected = { - "user": "squid", - "space": "clam", + "user": "oyster", + "space": "nudibranch", } path = ChatServiceClient.space_notification_setting_path(**expected) @@ -40077,8 +42603,8 @@ def test_parse_space_notification_setting_path(): def test_space_read_state_path(): - user = "whelk" - space = "octopus" + user = "cuttlefish" + space = "mussel" expected = "users/{user}/spaces/{space}/spaceReadState".format( user=user, space=space, @@ -40089,8 +42615,8 @@ def test_space_read_state_path(): def test_parse_space_read_state_path(): expected = { - "user": "oyster", - "space": "nudibranch", + "user": "winkle", + "space": "nautilus", } path = ChatServiceClient.space_read_state_path(**expected) @@ -40100,8 +42626,8 @@ def test_parse_space_read_state_path(): def test_thread_path(): - space = "cuttlefish" - thread = "mussel" + space = "scallop" + thread = "abalone" expected = "spaces/{space}/threads/{thread}".format( space=space, thread=thread, @@ -40112,8 +42638,8 @@ def test_thread_path(): def test_parse_thread_path(): expected = { - "space": "winkle", - "thread": "nautilus", + "space": "squid", + "thread": "clam", } path = ChatServiceClient.thread_path(**expected) @@ -40123,9 +42649,9 @@ def test_parse_thread_path(): def test_thread_read_state_path(): - user = "scallop" - space = "abalone" - thread = "squid" + user = "whelk" + space = "octopus" + thread = "oyster" expected = "users/{user}/spaces/{space}/threads/{thread}/threadReadState".format( user=user, space=space, @@ -40137,9 +42663,9 @@ def test_thread_read_state_path(): def test_parse_thread_read_state_path(): expected = { - "user": "clam", - "space": "whelk", - "thread": "octopus", + "user": "nudibranch", + "space": "cuttlefish", + "thread": "mussel", } path = ChatServiceClient.thread_read_state_path(**expected) @@ -40149,7 +42675,7 @@ def test_parse_thread_read_state_path(): def test_user_path(): - user = "oyster" + user = "winkle" expected = "users/{user}".format( user=user, ) @@ -40159,7 +42685,7 @@ def test_user_path(): def test_parse_user_path(): expected = { - "user": "nudibranch", + "user": "nautilus", } path = ChatServiceClient.user_path(**expected) @@ -40169,7 +42695,7 @@ def test_parse_user_path(): def test_common_billing_account_path(): - billing_account = "cuttlefish" + billing_account = "scallop" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -40179,7 +42705,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "mussel", + "billing_account": "abalone", } path = ChatServiceClient.common_billing_account_path(**expected) @@ -40189,7 +42715,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "winkle" + folder = "squid" expected = "folders/{folder}".format( folder=folder, ) @@ -40199,7 +42725,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nautilus", + "folder": "clam", } path = ChatServiceClient.common_folder_path(**expected) @@ -40209,7 +42735,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "scallop" + organization = "whelk" expected = "organizations/{organization}".format( organization=organization, ) @@ -40219,7 +42745,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "abalone", + "organization": "octopus", } path = ChatServiceClient.common_organization_path(**expected) @@ -40229,7 +42755,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "squid" + project = "oyster" expected = "projects/{project}".format( project=project, ) @@ -40239,7 +42765,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "clam", + "project": "nudibranch", } path = ChatServiceClient.common_project_path(**expected) @@ -40249,8 +42775,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "whelk" - location = "octopus" + project = "cuttlefish" + location = "mussel" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -40261,8 +42787,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "oyster", - "location": "nudibranch", + "project": "winkle", + "location": "nautilus", } path = ChatServiceClient.common_location_path(**expected) diff --git a/packages/google-cloud-agentregistry/google/cloud/agentregistry_v1/services/agent_registry/async_client.py b/packages/google-cloud-agentregistry/google/cloud/agentregistry_v1/services/agent_registry/async_client.py index 4295a2a41ae9..555116a2d475 100644 --- a/packages/google-cloud-agentregistry/google/cloud/agentregistry_v1/services/agent_registry/async_client.py +++ b/packages/google-cloud-agentregistry/google/cloud/agentregistry_v1/services/agent_registry/async_client.py @@ -2234,7 +2234,6 @@ async def sample_create_binding(): binding = agentregistry_v1.Binding() binding.auth_provider_binding.auth_provider = "auth_provider_value" binding.name = "name_value" - binding.source.identifier = "identifier_value" binding.target.identifier = "identifier_value" request = agentregistry_v1.CreateBindingRequest( @@ -2394,7 +2393,6 @@ async def sample_update_binding(): binding = agentregistry_v1.Binding() binding.auth_provider_binding.auth_provider = "auth_provider_value" binding.name = "name_value" - binding.source.identifier = "identifier_value" binding.target.identifier = "identifier_value" request = agentregistry_v1.UpdateBindingRequest( diff --git a/packages/google-cloud-agentregistry/google/cloud/agentregistry_v1/services/agent_registry/client.py b/packages/google-cloud-agentregistry/google/cloud/agentregistry_v1/services/agent_registry/client.py index 2e993a626c74..e52e4a3443f9 100644 --- a/packages/google-cloud-agentregistry/google/cloud/agentregistry_v1/services/agent_registry/client.py +++ b/packages/google-cloud-agentregistry/google/cloud/agentregistry_v1/services/agent_registry/client.py @@ -2566,7 +2566,6 @@ def sample_create_binding(): binding = agentregistry_v1.Binding() binding.auth_provider_binding.auth_provider = "auth_provider_value" binding.name = "name_value" - binding.source.identifier = "identifier_value" binding.target.identifier = "identifier_value" request = agentregistry_v1.CreateBindingRequest( @@ -2723,7 +2722,6 @@ def sample_update_binding(): binding = agentregistry_v1.Binding() binding.auth_provider_binding.auth_provider = "auth_provider_value" binding.name = "name_value" - binding.source.identifier = "identifier_value" binding.target.identifier = "identifier_value" request = agentregistry_v1.UpdateBindingRequest( diff --git a/packages/google-cloud-agentregistry/google/cloud/agentregistry_v1/types/binding.py b/packages/google-cloud-agentregistry/google/cloud/agentregistry_v1/types/binding.py index 20c8c29ab966..ff43f1188c72 100644 --- a/packages/google-cloud-agentregistry/google/cloud/agentregistry_v1/types/binding.py +++ b/packages/google-cloud-agentregistry/google/cloud/agentregistry_v1/types/binding.py @@ -49,7 +49,7 @@ class Binding(proto.Message): Optional. User-defined description of a Binding. Can have a maximum length of ``2048`` characters. source (google.cloud.agentregistry_v1.types.Binding.Source): - Required. The target Agent of the Binding. + Optional. The source Agent of the Binding. target (google.cloud.agentregistry_v1.types.Binding.Target): Required. The target Agent Registry Resource of the Binding. diff --git a/packages/google-cloud-agentregistry/samples/generated_samples/agentregistry_v1_generated_agent_registry_create_binding_async.py b/packages/google-cloud-agentregistry/samples/generated_samples/agentregistry_v1_generated_agent_registry_create_binding_async.py index f7da69d5fe62..3ed101ce7335 100644 --- a/packages/google-cloud-agentregistry/samples/generated_samples/agentregistry_v1_generated_agent_registry_create_binding_async.py +++ b/packages/google-cloud-agentregistry/samples/generated_samples/agentregistry_v1_generated_agent_registry_create_binding_async.py @@ -42,7 +42,6 @@ async def sample_create_binding(): binding = agentregistry_v1.Binding() binding.auth_provider_binding.auth_provider = "auth_provider_value" binding.name = "name_value" - binding.source.identifier = "identifier_value" binding.target.identifier = "identifier_value" request = agentregistry_v1.CreateBindingRequest( diff --git a/packages/google-cloud-agentregistry/samples/generated_samples/agentregistry_v1_generated_agent_registry_create_binding_sync.py b/packages/google-cloud-agentregistry/samples/generated_samples/agentregistry_v1_generated_agent_registry_create_binding_sync.py index 46ec90c345fa..04eaa6f17f26 100644 --- a/packages/google-cloud-agentregistry/samples/generated_samples/agentregistry_v1_generated_agent_registry_create_binding_sync.py +++ b/packages/google-cloud-agentregistry/samples/generated_samples/agentregistry_v1_generated_agent_registry_create_binding_sync.py @@ -42,7 +42,6 @@ def sample_create_binding(): binding = agentregistry_v1.Binding() binding.auth_provider_binding.auth_provider = "auth_provider_value" binding.name = "name_value" - binding.source.identifier = "identifier_value" binding.target.identifier = "identifier_value" request = agentregistry_v1.CreateBindingRequest( diff --git a/packages/google-cloud-agentregistry/samples/generated_samples/agentregistry_v1_generated_agent_registry_update_binding_async.py b/packages/google-cloud-agentregistry/samples/generated_samples/agentregistry_v1_generated_agent_registry_update_binding_async.py index 171617293dae..22d888d2682c 100644 --- a/packages/google-cloud-agentregistry/samples/generated_samples/agentregistry_v1_generated_agent_registry_update_binding_async.py +++ b/packages/google-cloud-agentregistry/samples/generated_samples/agentregistry_v1_generated_agent_registry_update_binding_async.py @@ -42,7 +42,6 @@ async def sample_update_binding(): binding = agentregistry_v1.Binding() binding.auth_provider_binding.auth_provider = "auth_provider_value" binding.name = "name_value" - binding.source.identifier = "identifier_value" binding.target.identifier = "identifier_value" request = agentregistry_v1.UpdateBindingRequest( diff --git a/packages/google-cloud-agentregistry/samples/generated_samples/agentregistry_v1_generated_agent_registry_update_binding_sync.py b/packages/google-cloud-agentregistry/samples/generated_samples/agentregistry_v1_generated_agent_registry_update_binding_sync.py index 4d9915341cdb..c4755ba9e5cd 100644 --- a/packages/google-cloud-agentregistry/samples/generated_samples/agentregistry_v1_generated_agent_registry_update_binding_sync.py +++ b/packages/google-cloud-agentregistry/samples/generated_samples/agentregistry_v1_generated_agent_registry_update_binding_sync.py @@ -42,7 +42,6 @@ def sample_update_binding(): binding = agentregistry_v1.Binding() binding.auth_provider_binding.auth_provider = "auth_provider_value" binding.name = "name_value" - binding.source.identifier = "identifier_value" binding.target.identifier = "identifier_value" request = agentregistry_v1.UpdateBindingRequest( diff --git a/packages/google-cloud-agentregistry/samples/generated_samples/snippet_metadata_google.cloud.agentregistry.v1.json b/packages/google-cloud-agentregistry/samples/generated_samples/snippet_metadata_google.cloud.agentregistry.v1.json index 9449de422052..da1133b61332 100644 --- a/packages/google-cloud-agentregistry/samples/generated_samples/snippet_metadata_google.cloud.agentregistry.v1.json +++ b/packages/google-cloud-agentregistry/samples/generated_samples/snippet_metadata_google.cloud.agentregistry.v1.json @@ -68,12 +68,12 @@ "regionTag": "agentregistry_v1_generated_AgentRegistry_CreateBinding_async", "segments": [ { - "end": 63, + "end": 62, "start": 27, "type": "FULL" }, { - "end": 63, + "end": 62, "start": 27, "type": "SHORT" }, @@ -83,18 +83,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 53, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 60, - "start": 54, + "end": 59, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 64, - "start": 61, + "end": 63, + "start": 60, "type": "RESPONSE_HANDLING" } ], @@ -156,12 +156,12 @@ "regionTag": "agentregistry_v1_generated_AgentRegistry_CreateBinding_sync", "segments": [ { - "end": 63, + "end": 62, "start": 27, "type": "FULL" }, { - "end": 63, + "end": 62, "start": 27, "type": "SHORT" }, @@ -171,18 +171,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 53, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 60, - "start": 54, + "end": 59, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 64, - "start": 61, + "end": 63, + "start": 60, "type": "RESPONSE_HANDLING" } ], @@ -2833,12 +2833,12 @@ "regionTag": "agentregistry_v1_generated_AgentRegistry_UpdateBinding_async", "segments": [ { - "end": 61, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 60, "start": 27, "type": "SHORT" }, @@ -2848,18 +2848,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], @@ -2917,12 +2917,12 @@ "regionTag": "agentregistry_v1_generated_AgentRegistry_UpdateBinding_sync", "segments": [ { - "end": 61, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 60, "start": 27, "type": "SHORT" }, @@ -2932,18 +2932,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], diff --git a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/types/table.py b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/types/table.py index 63e37cb22d50..84b3fee29a34 100644 --- a/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/types/table.py +++ b/packages/google-cloud-bigtable/google/cloud/bigtable_admin_v2/types/table.py @@ -169,6 +169,11 @@ class Table(proto.Message): disabled. This field is a member of `oneof`_ ``automated_backup_config``. + effective_automated_backup_policy (google.cloud.bigtable_admin_v2.types.Table.AutomatedBackupPolicy): + Output only. The effective automated backup policy applied + to the table. This represents the policy actually in effect, + which may be a system-default policy if the user has not + explicitly configured one. Views: ``SCHEMA_VIEW``, ``FULL``. tiered_storage_config (google.cloud.bigtable_admin_v2.types.TieredStorageConfig): Rules to specify what data is stored in each storage tier. Different tiers store data @@ -374,6 +379,20 @@ class AutomatedBackupPolicy(proto.Message): Locations are in the format ``projects/{project}/locations/{zone}``. This field can only set for tables in Enterprise Plus instances. + keep_hot_duration (google.protobuf.duration_pb2.Duration): + Optional. The amount of time that the automated backups + remain hot. If specified, the backups created by this policy + are ``HOT`` backups. If not specified, the backups are + ``STANDARD`` backups. + + The value must be at least 24 hours and at most 10 days, and + can't exceed the policy's ``retention_period``. + + Only SSD instances support ``HOT`` automated backups. + disabled (bool): + Optional. If ``true``, automated backups are explicitly + disabled on this table. This allows users to opt out of + default enablement. """ retention_period: duration_pb2.Duration = proto.Field( @@ -390,6 +409,15 @@ class AutomatedBackupPolicy(proto.Message): proto.STRING, number=3, ) + keep_hot_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + disabled: bool = proto.Field( + proto.BOOL, + number=5, + ) name: str = proto.Field( proto.STRING, @@ -432,6 +460,11 @@ class AutomatedBackupPolicy(proto.Message): oneof="automated_backup_config", message=AutomatedBackupPolicy, ) + effective_automated_backup_policy: AutomatedBackupPolicy = proto.Field( + proto.MESSAGE, + number=19, + message=AutomatedBackupPolicy, + ) tiered_storage_config: "TieredStorageConfig" = proto.Field( proto.MESSAGE, number=14, diff --git a/packages/google-cloud-bigtable/tests/unit/gapic/bigtable_admin_v2/test_bigtable_table_admin.py b/packages/google-cloud-bigtable/tests/unit/gapic/bigtable_admin_v2/test_bigtable_table_admin.py index db33c7d62990..147b376f55d0 100644 --- a/packages/google-cloud-bigtable/tests/unit/gapic/bigtable_admin_v2/test_bigtable_table_admin.py +++ b/packages/google-cloud-bigtable/tests/unit/gapic/bigtable_admin_v2/test_bigtable_table_admin.py @@ -22749,7 +22749,10 @@ def test_update_table_rest_call_success(request_type): "retention_period": {}, "frequency": {}, "locations": ["locations_value1", "locations_value2"], + "keep_hot_duration": {}, + "disabled": True, }, + "effective_automated_backup_policy": {}, "tiered_storage_config": {"infrequent_access": {"include_if_older_than": {}}}, "row_key_schema": { "fields": [ diff --git a/packages/google-cloud-geminidataanalytics/docs/geminidataanalytics_v1alpha/data_a2a_service.rst b/packages/google-cloud-geminidataanalytics/docs/geminidataanalytics_v1alpha/data_a2a_service.rst new file mode 100644 index 000000000000..6f3ca6ac36de --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/docs/geminidataanalytics_v1alpha/data_a2a_service.rst @@ -0,0 +1,6 @@ +DataA2AService +-------------------------------- + +.. automodule:: google.cloud.geminidataanalytics_v1alpha.services.data_a2a_service + :members: + :inherited-members: diff --git a/packages/google-cloud-geminidataanalytics/docs/geminidataanalytics_v1alpha/services_.rst b/packages/google-cloud-geminidataanalytics/docs/geminidataanalytics_v1alpha/services_.rst index 57e2ff430377..6c3c0ca2c0aa 100644 --- a/packages/google-cloud-geminidataanalytics/docs/geminidataanalytics_v1alpha/services_.rst +++ b/packages/google-cloud-geminidataanalytics/docs/geminidataanalytics_v1alpha/services_.rst @@ -3,5 +3,6 @@ Services for Google Cloud Geminidataanalytics v1alpha API .. toctree:: :maxdepth: 2 + data_a2a_service data_agent_service data_chat_service diff --git a/packages/google-cloud-geminidataanalytics/docs/geminidataanalytics_v1beta/data_a2a_service.rst b/packages/google-cloud-geminidataanalytics/docs/geminidataanalytics_v1beta/data_a2a_service.rst new file mode 100644 index 000000000000..9e4b77e5dc3e --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/docs/geminidataanalytics_v1beta/data_a2a_service.rst @@ -0,0 +1,6 @@ +DataA2AService +-------------------------------- + +.. automodule:: google.cloud.geminidataanalytics_v1beta.services.data_a2a_service + :members: + :inherited-members: diff --git a/packages/google-cloud-geminidataanalytics/docs/geminidataanalytics_v1beta/services_.rst b/packages/google-cloud-geminidataanalytics/docs/geminidataanalytics_v1beta/services_.rst index 753bd69465da..8255d1413462 100644 --- a/packages/google-cloud-geminidataanalytics/docs/geminidataanalytics_v1beta/services_.rst +++ b/packages/google-cloud-geminidataanalytics/docs/geminidataanalytics_v1beta/services_.rst @@ -3,5 +3,6 @@ Services for Google Cloud Geminidataanalytics v1beta API .. toctree:: :maxdepth: 2 + data_a2a_service data_agent_service data_chat_service diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics/__init__.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics/__init__.py index 70ca234d8777..32492bc222dc 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics/__init__.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics/__init__.py @@ -40,6 +40,7 @@ Context, ConversationOptions, DatasourceOptions, + DynamicField, ExampleQuery, GlossaryTerm, LookerGoldenQuery, @@ -56,6 +57,7 @@ GetConversationRequest, ListConversationsRequest, ListConversationsResponse, + UpdateConversationRequest, ) from google.cloud.geminidataanalytics_v1.types.credentials import ( Credentials, @@ -71,6 +73,11 @@ ListDataAgentsRequest, ListDataAgentsResponse, OperationMetadata, + RetrieveAgentOpsObservabilityRequest, + RetrieveAgentOpsObservabilityResponse, + SetAgentOpsObservabilityMetadata, + SetAgentOpsObservabilityRequest, + SetAgentOpsObservabilityResponse, UpdateDataAgentRequest, ) from google.cloud.geminidataanalytics_v1.types.data_analytics_agent import ( @@ -137,6 +144,7 @@ "Context", "ConversationOptions", "DatasourceOptions", + "DynamicField", "ExampleQuery", "GlossaryTerm", "LookerGoldenQuery", @@ -151,6 +159,7 @@ "GetConversationRequest", "ListConversationsRequest", "ListConversationsResponse", + "UpdateConversationRequest", "Credentials", "OAuthCredentials", "DataAgent", @@ -162,6 +171,11 @@ "ListDataAgentsRequest", "ListDataAgentsResponse", "OperationMetadata", + "RetrieveAgentOpsObservabilityRequest", + "RetrieveAgentOpsObservabilityResponse", + "SetAgentOpsObservabilityMetadata", + "SetAgentOpsObservabilityRequest", + "SetAgentOpsObservabilityResponse", "UpdateDataAgentRequest", "DataAnalyticsAgent", "AnalysisEvent", diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/__init__.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/__init__.py index 366a76a3dae6..e195a7efb5bc 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/__init__.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/__init__.py @@ -57,6 +57,7 @@ Context, ConversationOptions, DatasourceOptions, + DynamicField, ExampleQuery, GlossaryTerm, LookerGoldenQuery, @@ -73,6 +74,7 @@ GetConversationRequest, ListConversationsRequest, ListConversationsResponse, + UpdateConversationRequest, ) from .types.credentials import Credentials, OAuthCredentials from .types.data_agent import DataAgent @@ -85,6 +87,11 @@ ListDataAgentsRequest, ListDataAgentsResponse, OperationMetadata, + RetrieveAgentOpsObservabilityRequest, + RetrieveAgentOpsObservabilityResponse, + SetAgentOpsObservabilityMetadata, + SetAgentOpsObservabilityRequest, + SetAgentOpsObservabilityResponse, UpdateDataAgentRequest, ) from .types.data_analytics_agent import DataAnalyticsAgent @@ -179,6 +186,7 @@ "DatasourceReferences", "DeleteConversationRequest", "DeleteDataAgentRequest", + "DynamicField", "ErrorMessage", "ExampleQueries", "ExampleQuery", @@ -206,15 +214,21 @@ "PrivateLookerInstanceInfo", "QueryParameter", "QueryParameterValues", + "RetrieveAgentOpsObservabilityRequest", + "RetrieveAgentOpsObservabilityResponse", "Schema", "SchemaMessage", "SchemaQuery", "SchemaResult", + "SetAgentOpsObservabilityMetadata", + "SetAgentOpsObservabilityRequest", + "SetAgentOpsObservabilityResponse", "StorageMessage", "StudioDatasourceReference", "StudioDatasourceReferences", "SystemMessage", "TextMessage", + "UpdateConversationRequest", "UpdateDataAgentRequest", "UserFunctions", "UserMessage", diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/gapic_metadata.json b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/gapic_metadata.json index b9fa8e74f243..3bfda63c7c3e 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/gapic_metadata.json +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/gapic_metadata.json @@ -50,6 +50,16 @@ "list_data_agents" ] }, + "RetrieveAgentOpsObservability": { + "methods": [ + "retrieve_agent_ops_observability" + ] + }, + "SetAgentOpsObservability": { + "methods": [ + "set_agent_ops_observability" + ] + }, "SetIamPolicy": { "methods": [ "set_iam_policy" @@ -110,6 +120,16 @@ "list_data_agents" ] }, + "RetrieveAgentOpsObservability": { + "methods": [ + "retrieve_agent_ops_observability" + ] + }, + "SetAgentOpsObservability": { + "methods": [ + "set_agent_ops_observability" + ] + }, "SetIamPolicy": { "methods": [ "set_iam_policy" @@ -170,6 +190,16 @@ "list_data_agents" ] }, + "RetrieveAgentOpsObservability": { + "methods": [ + "retrieve_agent_ops_observability" + ] + }, + "SetAgentOpsObservability": { + "methods": [ + "set_agent_ops_observability" + ] + }, "SetIamPolicy": { "methods": [ "set_iam_policy" @@ -223,6 +253,11 @@ "methods": [ "list_messages" ] + }, + "UpdateConversation": { + "methods": [ + "update_conversation" + ] } } }, @@ -258,6 +293,11 @@ "methods": [ "list_messages" ] + }, + "UpdateConversation": { + "methods": [ + "update_conversation" + ] } } }, @@ -293,6 +333,11 @@ "methods": [ "list_messages" ] + }, + "UpdateConversation": { + "methods": [ + "update_conversation" + ] } } } diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/async_client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/async_client.py index d84f4960911f..e4ed34ba29ec 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/async_client.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/async_client.py @@ -59,6 +59,7 @@ data_agent, data_agent_service, data_analytics_agent, + datasource, ) from google.cloud.geminidataanalytics_v1.types import data_agent as gcg_data_agent @@ -1730,6 +1731,290 @@ async def sample_set_iam_policy(): # Done; return the response. return response + async def set_agent_ops_observability( + self, + request: Optional[ + Union[data_agent_service.SetAgentOpsObservabilityRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + telemetry_enabled: Optional[bool] = None, + data_source_type: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Enables/Disables required GCP services and configures + AgentOps observability settings calling the Admin + Settings executable node to update the AgentOps + Observability feature. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1 + + async def sample_set_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1.DataAgentServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1.SetAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + operation = await client.set_agent_ops_observability(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.geminidataanalytics_v1.types.SetAgentOpsObservabilityRequest, dict]]): + The request object. Request for SetAgentOpsObservability. + parent (:class:`str`): + Required. Parent value for + SetAgentOpsObservabilityRequest. Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + telemetry_enabled (:class:`bool`): + Optional. Whether to enable or disable AgentOps + observability. When update_mask is provided, this field + is ignored unless specified in the mask. + + This corresponds to the ``telemetry_enabled`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_source_type (:class:`str`): + Required. The data source type for + which to set observability settings. + Examples: "bigquery", "looker" + + This corresponds to the ``data_source_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.geminidataanalytics_v1.types.SetAgentOpsObservabilityResponse` + Response for SetAgentOpsObservability. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, telemetry_enabled, data_source_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, data_agent_service.SetAgentOpsObservabilityRequest): + request = data_agent_service.SetAgentOpsObservabilityRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if telemetry_enabled is not None: + request.telemetry_enabled = telemetry_enabled + if data_source_type is not None: + request.data_source_type = data_source_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.set_agent_ops_observability + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + data_agent_service.SetAgentOpsObservabilityResponse, + metadata_type=data_agent_service.SetAgentOpsObservabilityMetadata, + ) + + # Done; return the response. + return response + + async def retrieve_agent_ops_observability( + self, + request: Optional[ + Union[data_agent_service.RetrieveAgentOpsObservabilityRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + data_source_type: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_agent_service.RetrieveAgentOpsObservabilityResponse: + r"""Gets AgentOps observability settings and status of + required services. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1 + + async def sample_retrieve_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1.DataAgentServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1.RetrieveAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + response = await client.retrieve_agent_ops_observability(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.geminidataanalytics_v1.types.RetrieveAgentOpsObservabilityRequest, dict]]): + The request object. Request for + RetrieveAgentOpsObservability. + parent (:class:`str`): + Required. Parent value for + RetrieveAgentOpsObservabilityRequest. + Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_source_type (:class:`str`): + Required. The data source type for + which to retrieve observability + settings. Examples: "bigquery", "looker" + + This corresponds to the ``data_source_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1.types.RetrieveAgentOpsObservabilityResponse: + Response for + RetrieveAgentOpsObservability. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, data_source_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, data_agent_service.RetrieveAgentOpsObservabilityRequest + ): + request = data_agent_service.RetrieveAgentOpsObservabilityRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if data_source_type is not None: + request.data_source_type = data_source_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.retrieve_agent_ops_observability + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def list_operations( self, request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/client.py index f6d56d45f756..d871862bbe52 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/client.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/client.py @@ -83,6 +83,7 @@ data_agent, data_agent_service, data_analytics_agent, + datasource, ) from google.cloud.geminidataanalytics_v1.types import data_agent as gcg_data_agent @@ -2027,6 +2028,288 @@ def sample_set_iam_policy(): # Done; return the response. return response + def set_agent_ops_observability( + self, + request: Optional[ + Union[data_agent_service.SetAgentOpsObservabilityRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + telemetry_enabled: Optional[bool] = None, + data_source_type: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Enables/Disables required GCP services and configures + AgentOps observability settings calling the Admin + Settings executable node to update the AgentOps + Observability feature. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1 + + def sample_set_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1.DataAgentServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1.SetAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + operation = client.set_agent_ops_observability(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.geminidataanalytics_v1.types.SetAgentOpsObservabilityRequest, dict]): + The request object. Request for SetAgentOpsObservability. + parent (str): + Required. Parent value for + SetAgentOpsObservabilityRequest. Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + telemetry_enabled (bool): + Optional. Whether to enable or disable AgentOps + observability. When update_mask is provided, this field + is ignored unless specified in the mask. + + This corresponds to the ``telemetry_enabled`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_source_type (str): + Required. The data source type for + which to set observability settings. + Examples: "bigquery", "looker" + + This corresponds to the ``data_source_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.geminidataanalytics_v1.types.SetAgentOpsObservabilityResponse` + Response for SetAgentOpsObservability. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, telemetry_enabled, data_source_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, data_agent_service.SetAgentOpsObservabilityRequest): + request = data_agent_service.SetAgentOpsObservabilityRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if telemetry_enabled is not None: + request.telemetry_enabled = telemetry_enabled + if data_source_type is not None: + request.data_source_type = data_source_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.set_agent_ops_observability + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + data_agent_service.SetAgentOpsObservabilityResponse, + metadata_type=data_agent_service.SetAgentOpsObservabilityMetadata, + ) + + # Done; return the response. + return response + + def retrieve_agent_ops_observability( + self, + request: Optional[ + Union[data_agent_service.RetrieveAgentOpsObservabilityRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + data_source_type: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_agent_service.RetrieveAgentOpsObservabilityResponse: + r"""Gets AgentOps observability settings and status of + required services. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1 + + def sample_retrieve_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1.DataAgentServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1.RetrieveAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + response = client.retrieve_agent_ops_observability(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.geminidataanalytics_v1.types.RetrieveAgentOpsObservabilityRequest, dict]): + The request object. Request for + RetrieveAgentOpsObservability. + parent (str): + Required. Parent value for + RetrieveAgentOpsObservabilityRequest. + Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_source_type (str): + Required. The data source type for + which to retrieve observability + settings. Examples: "bigquery", "looker" + + This corresponds to the ``data_source_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1.types.RetrieveAgentOpsObservabilityResponse: + Response for + RetrieveAgentOpsObservability. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, data_source_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, data_agent_service.RetrieveAgentOpsObservabilityRequest + ): + request = data_agent_service.RetrieveAgentOpsObservabilityRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if data_source_type is not None: + request.data_source_type = data_source_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.retrieve_agent_ops_observability + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "DataAgentServiceClient": return self diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/base.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/base.py index 7d4b77175ade..22acbb52bafb 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/base.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/base.py @@ -201,6 +201,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.set_agent_ops_observability: gapic_v1.method.wrap_method( + self.set_agent_ops_observability, + default_timeout=None, + client_info=client_info, + ), + self.retrieve_agent_ops_observability: gapic_v1.method.wrap_method( + self.retrieve_agent_ops_observability, + default_timeout=None, + client_info=client_info, + ), self.get_location: gapic_v1.method.wrap_method( self.get_location, default_timeout=None, @@ -352,6 +362,27 @@ def set_iam_policy( ]: raise NotImplementedError() + @property + def set_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.SetAgentOpsObservabilityRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def retrieve_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.RetrieveAgentOpsObservabilityRequest], + Union[ + data_agent_service.RetrieveAgentOpsObservabilityResponse, + Awaitable[data_agent_service.RetrieveAgentOpsObservabilityResponse], + ], + ]: + raise NotImplementedError() + @property def list_operations( self, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/grpc.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/grpc.py index 2dd39ac31ed9..6b4de6884e91 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/grpc.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/grpc.py @@ -656,6 +656,72 @@ def set_iam_policy( ) return self._stubs["set_iam_policy"] + @property + def set_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.SetAgentOpsObservabilityRequest], operations_pb2.Operation + ]: + r"""Return a callable for the set agent ops observability method over gRPC. + + Enables/Disables required GCP services and configures + AgentOps observability settings calling the Admin + Settings executable node to update the AgentOps + Observability feature. + + Returns: + Callable[[~.SetAgentOpsObservabilityRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent_ops_observability" not in self._stubs: + self._stubs["set_agent_ops_observability"] = ( + self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1.DataAgentService/SetAgentOpsObservability", + request_serializer=data_agent_service.SetAgentOpsObservabilityRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["set_agent_ops_observability"] + + @property + def retrieve_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.RetrieveAgentOpsObservabilityRequest], + data_agent_service.RetrieveAgentOpsObservabilityResponse, + ]: + r"""Return a callable for the retrieve agent ops + observability method over gRPC. + + Gets AgentOps observability settings and status of + required services. + + Returns: + Callable[[~.RetrieveAgentOpsObservabilityRequest], + ~.RetrieveAgentOpsObservabilityResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "retrieve_agent_ops_observability" not in self._stubs: + self._stubs["retrieve_agent_ops_observability"] = ( + self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1.DataAgentService/RetrieveAgentOpsObservability", + request_serializer=data_agent_service.RetrieveAgentOpsObservabilityRequest.serialize, + response_deserializer=data_agent_service.RetrieveAgentOpsObservabilityResponse.deserialize, + ) + ) + return self._stubs["retrieve_agent_ops_observability"] + def close(self): self._logged_channel.close() diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/grpc_asyncio.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/grpc_asyncio.py index a09fc8cecad3..f0112e62029f 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/grpc_asyncio.py @@ -668,6 +668,73 @@ def set_iam_policy( ) return self._stubs["set_iam_policy"] + @property + def set_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.SetAgentOpsObservabilityRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the set agent ops observability method over gRPC. + + Enables/Disables required GCP services and configures + AgentOps observability settings calling the Admin + Settings executable node to update the AgentOps + Observability feature. + + Returns: + Callable[[~.SetAgentOpsObservabilityRequest], + 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 "set_agent_ops_observability" not in self._stubs: + self._stubs["set_agent_ops_observability"] = ( + self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1.DataAgentService/SetAgentOpsObservability", + request_serializer=data_agent_service.SetAgentOpsObservabilityRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["set_agent_ops_observability"] + + @property + def retrieve_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.RetrieveAgentOpsObservabilityRequest], + Awaitable[data_agent_service.RetrieveAgentOpsObservabilityResponse], + ]: + r"""Return a callable for the retrieve agent ops + observability method over gRPC. + + Gets AgentOps observability settings and status of + required services. + + Returns: + Callable[[~.RetrieveAgentOpsObservabilityRequest], + Awaitable[~.RetrieveAgentOpsObservabilityResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "retrieve_agent_ops_observability" not in self._stubs: + self._stubs["retrieve_agent_ops_observability"] = ( + self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1.DataAgentService/RetrieveAgentOpsObservability", + request_serializer=data_agent_service.RetrieveAgentOpsObservabilityRequest.serialize, + response_deserializer=data_agent_service.RetrieveAgentOpsObservabilityResponse.deserialize, + ) + ) + return self._stubs["retrieve_agent_ops_observability"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -726,6 +793,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.set_agent_ops_observability: self._wrap_method( + self.set_agent_ops_observability, + default_timeout=None, + client_info=client_info, + ), + self.retrieve_agent_ops_observability: self._wrap_method( + self.retrieve_agent_ops_observability, + default_timeout=None, + client_info=client_info, + ), self.get_location: self._wrap_method( self.get_location, default_timeout=None, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/rest.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/rest.py index bc5460ed916e..e6e8f1d68602 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/rest.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/rest.py @@ -138,6 +138,22 @@ def post_list_data_agents(self, response): logging.log(f"Received response: {response}") return response + def pre_retrieve_agent_ops_observability(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_retrieve_agent_ops_observability(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_agent_ops_observability(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_agent_ops_observability(self, response): + logging.log(f"Received response: {response}") + return response + def pre_set_iam_policy(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -528,6 +544,107 @@ def post_list_data_agents_with_metadata( """ return response, metadata + def pre_retrieve_agent_ops_observability( + self, + request: data_agent_service.RetrieveAgentOpsObservabilityRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_agent_service.RetrieveAgentOpsObservabilityRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for retrieve_agent_ops_observability + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataAgentService server. + """ + return request, metadata + + def post_retrieve_agent_ops_observability( + self, response: data_agent_service.RetrieveAgentOpsObservabilityResponse + ) -> data_agent_service.RetrieveAgentOpsObservabilityResponse: + """Post-rpc interceptor for retrieve_agent_ops_observability + + DEPRECATED. Please use the `post_retrieve_agent_ops_observability_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DataAgentService server but before + it is returned to user code. This `post_retrieve_agent_ops_observability` interceptor runs + before the `post_retrieve_agent_ops_observability_with_metadata` interceptor. + """ + return response + + def post_retrieve_agent_ops_observability_with_metadata( + self, + response: data_agent_service.RetrieveAgentOpsObservabilityResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_agent_service.RetrieveAgentOpsObservabilityResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for retrieve_agent_ops_observability + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DataAgentService server but before it is returned to user code. + + We recommend only using this `post_retrieve_agent_ops_observability_with_metadata` + interceptor in new development instead of the `post_retrieve_agent_ops_observability` interceptor. + When both interceptors are used, this `post_retrieve_agent_ops_observability_with_metadata` interceptor runs after the + `post_retrieve_agent_ops_observability` interceptor. The (possibly modified) response returned by + `post_retrieve_agent_ops_observability` will be passed to + `post_retrieve_agent_ops_observability_with_metadata`. + """ + return response, metadata + + def pre_set_agent_ops_observability( + self, + request: data_agent_service.SetAgentOpsObservabilityRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_agent_service.SetAgentOpsObservabilityRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for set_agent_ops_observability + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataAgentService server. + """ + return request, metadata + + def post_set_agent_ops_observability( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for set_agent_ops_observability + + DEPRECATED. Please use the `post_set_agent_ops_observability_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DataAgentService server but before + it is returned to user code. This `post_set_agent_ops_observability` interceptor runs + before the `post_set_agent_ops_observability_with_metadata` interceptor. + """ + return response + + def post_set_agent_ops_observability_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for set_agent_ops_observability + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DataAgentService server but before it is returned to user code. + + We recommend only using this `post_set_agent_ops_observability_with_metadata` + interceptor in new development instead of the `post_set_agent_ops_observability` interceptor. + When both interceptors are used, this `post_set_agent_ops_observability_with_metadata` interceptor runs after the + `post_set_agent_ops_observability` interceptor. The (possibly modified) response returned by + `post_set_agent_ops_observability` will be passed to + `post_set_agent_ops_observability_with_metadata`. + """ + return response, metadata + def pre_set_iam_policy( self, request: iam_policy_pb2.SetIamPolicyRequest, @@ -2195,6 +2312,312 @@ def __call__( ) return resp + class _RetrieveAgentOpsObservability( + _BaseDataAgentServiceRestTransport._BaseRetrieveAgentOpsObservability, + DataAgentServiceRestStub, + ): + def __hash__(self): + return hash("DataAgentServiceRestTransport.RetrieveAgentOpsObservability") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: data_agent_service.RetrieveAgentOpsObservabilityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_agent_service.RetrieveAgentOpsObservabilityResponse: + r"""Call the retrieve agent ops + observability method over HTTP. + + Args: + request (~.data_agent_service.RetrieveAgentOpsObservabilityRequest): + The request object. Request for + RetrieveAgentOpsObservability. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.data_agent_service.RetrieveAgentOpsObservabilityResponse: + Response for + RetrieveAgentOpsObservability. + + """ + + http_options = _BaseDataAgentServiceRestTransport._BaseRetrieveAgentOpsObservability._get_http_options() + request, metadata = self._interceptor.pre_retrieve_agent_ops_observability( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataAgentServiceRestTransport._BaseRetrieveAgentOpsObservability, + "_BaseRetrieveAgentOpsObservability__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1.DataAgentServiceClient.RetrieveAgentOpsObservability", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1.DataAgentService", + "rpcName": "RetrieveAgentOpsObservability", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataAgentServiceRestTransport._RetrieveAgentOpsObservability._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = data_agent_service.RetrieveAgentOpsObservabilityResponse() + pb_resp = data_agent_service.RetrieveAgentOpsObservabilityResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_retrieve_agent_ops_observability(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_retrieve_agent_ops_observability_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = data_agent_service.RetrieveAgentOpsObservabilityResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1.DataAgentServiceClient.retrieve_agent_ops_observability", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1.DataAgentService", + "rpcName": "RetrieveAgentOpsObservability", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SetAgentOpsObservability( + _BaseDataAgentServiceRestTransport._BaseSetAgentOpsObservability, + DataAgentServiceRestStub, + ): + def __hash__(self): + return hash("DataAgentServiceRestTransport.SetAgentOpsObservability") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: data_agent_service.SetAgentOpsObservabilityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the set agent ops + observability method over HTTP. + + Args: + request (~.data_agent_service.SetAgentOpsObservabilityRequest): + The request object. Request for SetAgentOpsObservability. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseDataAgentServiceRestTransport._BaseSetAgentOpsObservability._get_http_options() + request, metadata = self._interceptor.pre_set_agent_ops_observability( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataAgentServiceRestTransport._BaseSetAgentOpsObservability, + "_BaseSetAgentOpsObservability__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1.DataAgentServiceClient.SetAgentOpsObservability", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1.DataAgentService", + "rpcName": "SetAgentOpsObservability", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + DataAgentServiceRestTransport._SetAgentOpsObservability._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_set_agent_ops_observability(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_set_agent_ops_observability_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1.DataAgentServiceClient.set_agent_ops_observability", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1.DataAgentService", + "rpcName": "SetAgentOpsObservability", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _SetIamPolicy( _BaseDataAgentServiceRestTransport._BaseSetIamPolicy, DataAgentServiceRestStub ): @@ -2794,6 +3217,31 @@ def list_data_agents( # In C++ this would require a dynamic_cast return self._ListDataAgents(self._session, self._host, self._interceptor) # type: ignore + @property + def retrieve_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.RetrieveAgentOpsObservabilityRequest], + data_agent_service.RetrieveAgentOpsObservabilityResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RetrieveAgentOpsObservability( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def set_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.SetAgentOpsObservabilityRequest], 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._SetAgentOpsObservability( + self._session, self._host, self._interceptor + ) # type: ignore + @property def set_iam_policy( self, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/rest_base.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/rest_base.py index 372a51e8686a..8e593b798610 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/rest_base.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_agent_service/transports/rest_base.py @@ -224,6 +224,41 @@ def _get_http_options(): ] return http_options + class _BaseRetrieveAgentOpsObservability: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "dataSourceType": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}:retrieveAgentOpsObservability", + }, + ] + return http_options + + class _BaseSetAgentOpsObservability: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/observabilitySettings:setAgentOpsObservability", + "body": "*", + }, + ] + return http_options + class _BaseSetIamPolicy: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/async_client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/async_client.py index 17c2c4858da8..d6d9440e732f 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/async_client.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/async_client.py @@ -46,6 +46,7 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore @@ -636,6 +637,136 @@ async def sample_delete_conversation(): metadata=metadata, ) + async def update_conversation( + self, + request: Optional[ + Union[gcg_conversation.UpdateConversationRequest, dict] + ] = None, + *, + conversation: Optional[gcg_conversation.Conversation] = 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, Union[str, bytes]]] = (), + ) -> gcg_conversation.Conversation: + r"""Updates a conversation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1 + + async def sample_update_conversation(): + # Create a client + client = geminidataanalytics_v1.DataChatServiceAsyncClient() + + # Initialize request argument(s) + conversation = geminidataanalytics_v1.Conversation() + conversation.agents = ['agents_value1', 'agents_value2'] + + request = geminidataanalytics_v1.UpdateConversationRequest( + conversation=conversation, + ) + + # Make the request + response = await client.update_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.geminidataanalytics_v1.types.UpdateConversationRequest, dict]]): + The request object. Request for updating a conversation. + conversation (:class:`google.cloud.geminidataanalytics_v1.types.Conversation`): + Required. The resource being updated. + This corresponds to the ``conversation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the Conversation resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields with non-default values + present in the request will be overwritten. If a + wildcard mask is provided, all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1.types.Conversation: + Message for a conversation. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [conversation, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcg_conversation.UpdateConversationRequest): + request = gcg_conversation.UpdateConversationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if conversation is not None: + request.conversation = conversation + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_conversation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("conversation.name", request.conversation.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def get_conversation( self, request: Optional[Union[conversation.GetConversationRequest, dict]] = None, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/client.py index 6d1e2fc1aef0..40af81c9f1ec 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/client.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/client.py @@ -69,6 +69,7 @@ _LOGGER = std_logging.getLogger(__name__) +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore @@ -966,6 +967,133 @@ def sample_delete_conversation(): metadata=metadata, ) + def update_conversation( + self, + request: Optional[ + Union[gcg_conversation.UpdateConversationRequest, dict] + ] = None, + *, + conversation: Optional[gcg_conversation.Conversation] = 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, Union[str, bytes]]] = (), + ) -> gcg_conversation.Conversation: + r"""Updates a conversation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1 + + def sample_update_conversation(): + # Create a client + client = geminidataanalytics_v1.DataChatServiceClient() + + # Initialize request argument(s) + conversation = geminidataanalytics_v1.Conversation() + conversation.agents = ['agents_value1', 'agents_value2'] + + request = geminidataanalytics_v1.UpdateConversationRequest( + conversation=conversation, + ) + + # Make the request + response = client.update_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.geminidataanalytics_v1.types.UpdateConversationRequest, dict]): + The request object. Request for updating a conversation. + conversation (google.cloud.geminidataanalytics_v1.types.Conversation): + Required. The resource being updated. + This corresponds to the ``conversation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Conversation resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields with non-default values + present in the request will be overwritten. If a + wildcard mask is provided, all fields will be + overwritten. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1.types.Conversation: + Message for a conversation. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [conversation, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcg_conversation.UpdateConversationRequest): + request = gcg_conversation.UpdateConversationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if conversation is not None: + request.conversation = conversation + 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_conversation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("conversation.name", request.conversation.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def get_conversation( self, request: Optional[Union[conversation.GetConversationRequest, dict]] = None, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/base.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/base.py index 1785d4643d25..68892f436588 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/base.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/base.py @@ -159,6 +159,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.update_conversation: gapic_v1.method.wrap_method( + self.update_conversation, + default_timeout=None, + client_info=client_info, + ), self.get_conversation: gapic_v1.method.wrap_method( self.get_conversation, default_timeout=None, @@ -242,6 +247,15 @@ def delete_conversation( ]: raise NotImplementedError() + @property + def update_conversation( + self, + ) -> Callable[ + [gcg_conversation.UpdateConversationRequest], + Union[gcg_conversation.Conversation, Awaitable[gcg_conversation.Conversation]], + ]: + raise NotImplementedError() + @property def get_conversation( self, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/grpc.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/grpc.py index dff71c35c9c2..744dd5aff46e 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/grpc.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/grpc.py @@ -414,6 +414,34 @@ def delete_conversation( ) return self._stubs["delete_conversation"] + @property + def update_conversation( + self, + ) -> Callable[ + [gcg_conversation.UpdateConversationRequest], gcg_conversation.Conversation + ]: + r"""Return a callable for the update conversation method over gRPC. + + Updates a conversation. + + Returns: + Callable[[~.UpdateConversationRequest], + ~.Conversation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation" not in self._stubs: + self._stubs["update_conversation"] = self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1.DataChatService/UpdateConversation", + request_serializer=gcg_conversation.UpdateConversationRequest.serialize, + response_deserializer=gcg_conversation.Conversation.deserialize, + ) + return self._stubs["update_conversation"] + @property def get_conversation( self, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/grpc_asyncio.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/grpc_asyncio.py index a31ac3ae92d2..b06629d02164 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/grpc_asyncio.py @@ -425,6 +425,35 @@ def delete_conversation( ) return self._stubs["delete_conversation"] + @property + def update_conversation( + self, + ) -> Callable[ + [gcg_conversation.UpdateConversationRequest], + Awaitable[gcg_conversation.Conversation], + ]: + r"""Return a callable for the update conversation method over gRPC. + + Updates a conversation. + + Returns: + Callable[[~.UpdateConversationRequest], + Awaitable[~.Conversation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation" not in self._stubs: + self._stubs["update_conversation"] = self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1.DataChatService/UpdateConversation", + request_serializer=gcg_conversation.UpdateConversationRequest.serialize, + response_deserializer=gcg_conversation.Conversation.deserialize, + ) + return self._stubs["update_conversation"] + @property def get_conversation( self, @@ -530,6 +559,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.update_conversation: self._wrap_method( + self.update_conversation, + default_timeout=None, + client_info=client_info, + ), self.get_conversation: self._wrap_method( self.get_conversation, default_timeout=None, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/rest.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/rest.py index ca2441268b83..fd4214decaa0 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/rest.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/rest.py @@ -120,6 +120,14 @@ def post_list_messages(self, response): logging.log(f"Received response: {response}") return response + def pre_update_conversation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_conversation(self, response): + logging.log(f"Received response: {response}") + return response + transport = DataChatServiceRestTransport(interceptor=MyCustomDataChatServiceInterceptor()) client = DataChatServiceClient(transport=transport) @@ -385,6 +393,55 @@ def post_list_messages_with_metadata( """ return response, metadata + def pre_update_conversation( + self, + request: gcg_conversation.UpdateConversationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcg_conversation.UpdateConversationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataChatService server. + """ + return request, metadata + + def post_update_conversation( + self, response: gcg_conversation.Conversation + ) -> gcg_conversation.Conversation: + """Post-rpc interceptor for update_conversation + + DEPRECATED. Please use the `post_update_conversation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DataChatService server but before + it is returned to user code. This `post_update_conversation` interceptor runs + before the `post_update_conversation_with_metadata` interceptor. + """ + return response + + def post_update_conversation_with_metadata( + self, + response: gcg_conversation.Conversation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcg_conversation.Conversation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_conversation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DataChatService server but before it is returned to user code. + + We recommend only using this `post_update_conversation_with_metadata` + interceptor in new development instead of the `post_update_conversation` interceptor. + When both interceptors are used, this `post_update_conversation_with_metadata` interceptor runs after the + `post_update_conversation` interceptor. The (possibly modified) response returned by + `post_update_conversation` will be passed to + `post_update_conversation_with_metadata`. + """ + return response, metadata + def pre_get_location( self, request: locations_pb2.GetLocationRequest, @@ -1467,6 +1524,154 @@ def __call__( ) return resp + class _UpdateConversation( + _BaseDataChatServiceRestTransport._BaseUpdateConversation, + DataChatServiceRestStub, + ): + def __hash__(self): + return hash("DataChatServiceRestTransport.UpdateConversation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gcg_conversation.UpdateConversationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcg_conversation.Conversation: + r"""Call the update conversation method over HTTP. + + Args: + request (~.gcg_conversation.UpdateConversationRequest): + The request object. Request for updating a conversation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcg_conversation.Conversation: + Message for a conversation. + """ + + http_options = _BaseDataChatServiceRestTransport._BaseUpdateConversation._get_http_options() + request, metadata = self._interceptor.pre_update_conversation( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataChatServiceRestTransport._BaseUpdateConversation, + "_BaseUpdateConversation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1.DataChatServiceClient.UpdateConversation", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1.DataChatService", + "rpcName": "UpdateConversation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataChatServiceRestTransport._UpdateConversation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcg_conversation.Conversation() + pb_resp = gcg_conversation.Conversation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_conversation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_conversation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcg_conversation.Conversation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1.DataChatServiceClient.update_conversation", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1.DataChatService", + "rpcName": "UpdateConversation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + @property def chat( self, @@ -1521,6 +1726,16 @@ def list_messages( # In C++ this would require a dynamic_cast return self._ListMessages(self._session, self._host, self._interceptor) # type: ignore + @property + def update_conversation( + self, + ) -> Callable[ + [gcg_conversation.UpdateConversationRequest], gcg_conversation.Conversation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateConversation(self._session, self._host, self._interceptor) # type: ignore + @property def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/rest_base.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/rest_base.py index 63533b25dfad..2bb0cfd1b10b 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/rest_base.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/services/data_chat_service/transports/rest_base.py @@ -189,6 +189,23 @@ def _get_http_options(): ] return http_options + class _BaseUpdateConversation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{conversation.name=projects/*/locations/*/conversations/*}", + "body": "conversation", + }, + ] + return http_options + class _BaseGetLocation: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/__init__.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/__init__.py index 8143faecfa14..ea010f78ad35 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/__init__.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/__init__.py @@ -23,6 +23,7 @@ Context, ConversationOptions, DatasourceOptions, + DynamicField, ExampleQuery, GlossaryTerm, LookerGoldenQuery, @@ -39,6 +40,7 @@ GetConversationRequest, ListConversationsRequest, ListConversationsResponse, + UpdateConversationRequest, ) from .credentials import ( Credentials, @@ -56,6 +58,11 @@ ListDataAgentsRequest, ListDataAgentsResponse, OperationMetadata, + RetrieveAgentOpsObservabilityRequest, + RetrieveAgentOpsObservabilityResponse, + SetAgentOpsObservabilityMetadata, + SetAgentOpsObservabilityRequest, + SetAgentOpsObservabilityResponse, UpdateDataAgentRequest, ) from .data_analytics_agent import ( @@ -118,6 +125,7 @@ "Context", "ConversationOptions", "DatasourceOptions", + "DynamicField", "ExampleQuery", "GlossaryTerm", "LookerGoldenQuery", @@ -132,6 +140,7 @@ "GetConversationRequest", "ListConversationsRequest", "ListConversationsResponse", + "UpdateConversationRequest", "Credentials", "OAuthCredentials", "DataAgent", @@ -143,6 +152,11 @@ "ListDataAgentsRequest", "ListDataAgentsResponse", "OperationMetadata", + "RetrieveAgentOpsObservabilityRequest", + "RetrieveAgentOpsObservabilityResponse", + "SetAgentOpsObservabilityMetadata", + "SetAgentOpsObservabilityRequest", + "SetAgentOpsObservabilityResponse", "UpdateDataAgentRequest", "DataAnalyticsAgent", "AnalysisEvent", diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/context.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/context.py index 5dcb26f7012a..65dc4055ed85 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/context.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/context.py @@ -34,6 +34,7 @@ "MatchedQuery", "QueryParameterValues", "LookerGoldenQuery", + "DynamicField", "LookerQuery", "GlossaryTerm", "ConversationOptions", @@ -59,6 +60,9 @@ class Context(proto.Message): etc) and system instructions (e.g., answer like a Pirate) can help the model understand the business context around a user question. + + Must be at most 250,000 bytes (approx. 250,000 + characters for English text). datasource_references (google.cloud.geminidataanalytics_v1.types.DatasourceReferences): Required. Data sources that are available for answering the question. @@ -302,13 +306,18 @@ class ExampleQuery(proto.Message): Optional. The SQL query that should be generated to answer the natural language question. For example: "SELECT COUNT(\*) FROM orders WHERE order_date BETWEEN '2024-01-01' - AND '2024-01-31'". + AND '2024-01-31'" + + Must be at most 50,000 bytes (approx. 50,000 characters). This field is a member of `oneof`_ ``query``. natural_language_question (str): Optional. A natural language question that a user might ask. For example: "How many orders - were placed last month?". + were placed last month?" + + Must be at most 2,000 bytes (approx. 2,000 + characters). parameters (MutableSequence[google.cloud.geminidataanalytics_v1.types.QueryParameter]): Optional. The list of query parameters. Example: The parameterized SQL query "SELECT \* FROM my_table WHERE id = @@ -425,7 +434,10 @@ class LookerGoldenQuery(proto.Message): natural_language_questions (MutableSequence[str]): Optional. Natural language questions that a user might ask. For example: "How many orders - were placed last month?". + were placed last month?" + + Must be at most 2,000 bytes per question + (approx. 2,000 characters). looker_query (google.cloud.geminidataanalytics_v1.types.LookerQuery): Optional. The Looker Query corresponding to the natural language questions. @@ -442,6 +454,170 @@ class LookerGoldenQuery(proto.Message): ) +class DynamicField(proto.Message): + r"""A dynamic field in Looker (Custom Dimension, Custom Measure, + or Table Calculation). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + category (str): + Optional. The type of dynamic field: dimension, measure, + table_calculation. Looker can use the category type to + specify the name of the dynamic field. However, Looker + Conversational Analytics keeps the category separate from + the name of the dynamic field. For more details, see + https://docs.cloud.google.com/looker/docs/reference/param-lookml-dashboard-table-chart#dynamic_fields. + + This field is a member of `oneof`_ ``_category``. + name (str): + Optional. The name of the dynamic field in + LookML. + + This field is a member of `oneof`_ ``_name``. + label (str): + Optional. The label defines the display name + of the dynamic field. + + This field is a member of `oneof`_ ``_label``. + based_on (str): + Optional. For custom measures, this + identifies the measure the field is based on. + + This field is a member of `oneof`_ ``_based_on``. + type_ (str): + Optional. For custom measures, this + identifies the type of aggregation (e.g. sum). + + This field is a member of `oneof`_ ``_type``. + description (str): + Optional. Description of the dynamic field. + + This field is a member of `oneof`_ ``_description``. + expression (str): + Optional. Looker expression to create a table + calculation. + + This field is a member of `oneof`_ ``_expression``. + filter_expression (str): + Optional. Looker expression to filter a base + measure. + + This field is a member of `oneof`_ ``_filter_expression``. + value_format (str): + Optional. Value format for the dynamic field. + + This field is a member of `oneof`_ ``_value_format``. + value_format_name (str): + Optional. Value format name for the dynamic + field if using a default named format. + + This field is a member of `oneof`_ ``_value_format_name``. + calculation_type (str): + Optional. Calculation type for table calculations. Refer to + https://docs.cloud.google.com/looker/docs/reference/param-lookml-dashboard-table-chart#calculation_type + for all possible values depending on the ``category`` of + dynamic field. + + This field is a member of `oneof`_ ``_calculation_type``. + args (MutableSequence[str]): + Optional. Arguments for custom groups, custom bins, or + shortcut calculations. For more details, refer to + https://docs.cloud.google.com/looker/docs/reference/param-lookml-dashboard-table-chart#args_for_custom_groups + kind_hint (str): + Optional. Identifies whether the dynamic + field returns a dimension or measure. + + This field is a member of `oneof`_ ``_kind_hint``. + type_hint (str): + Optional. Identifies the data type the + dynamic field's expression should produce. + + This field is a member of `oneof`_ ``_type_hint``. + is_disabled (bool): + Optional. Whether the dynamic field is + disabled. + + This field is a member of `oneof`_ ``_is_disabled``. + """ + + category: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + name: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + label: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + based_on: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + type_: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + description: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + expression: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) + filter_expression: str = proto.Field( + proto.STRING, + number=8, + optional=True, + ) + value_format: str = proto.Field( + proto.STRING, + number=9, + optional=True, + ) + value_format_name: str = proto.Field( + proto.STRING, + number=10, + optional=True, + ) + calculation_type: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) + args: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=12, + ) + kind_hint: str = proto.Field( + proto.STRING, + number=13, + optional=True, + ) + type_hint: str = proto.Field( + proto.STRING, + number=14, + optional=True, + ) + is_disabled: bool = proto.Field( + proto.BOOL, + number=15, + optional=True, + ) + + class LookerQuery(proto.Message): r"""Looker Query Object `Looker API documentation `__. @@ -468,6 +644,9 @@ class LookerQuery(proto.Message): Optional. Limit in the query. This field is a member of `oneof`_ ``_limit``. + dynamic_fields (MutableSequence[google.cloud.geminidataanalytics_v1.types.DynamicField]): + Optional. The dynamic fields used in the + query. query_id (str): Optional. The primary identifier for the query resource in Looker, used for API operations. Maps to ``id`` (or @@ -536,6 +715,11 @@ class Filter(proto.Message): number=6, optional=True, ) + dynamic_fields: MutableSequence["DynamicField"] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message="DynamicField", + ) query_id: str = proto.Field( proto.STRING, number=10, @@ -555,13 +739,18 @@ class GlossaryTerm(proto.Message): display_name (str): Required. User friendly display name of the glossary term being defined. For example: "CTR", - "conversion rate", "pending". + "conversion rate", "pending" + + Must be at most 256 bytes. description (str): Required. The description or meaning of the term. For example: "Click-through rate", "The percentage of users who complete a desired action", "An order that is waiting to be - processed.". + processed." + + Must be at most 5,000 bytes (approx. 5,000 + characters). labels (MutableSequence[str]): Optional. A list of general purpose labels associated to this term. For example: ["click rate", "clickthrough", @@ -604,14 +793,13 @@ class Model(proto.Enum): Values: MODEL_UNSPECIFIED (0): - No model specified. The model may be set on the chat - request, or the default model will be used. Currently, this - is ``gemini-3.0-flash-preview``. + No model specified. The model may be set on + the chat request, or the default model will be + used. LATEST_GA_MODEL (1): - Use the most up-to-date non-preview model. Currently, this - is ``gemini-2.5-flash``. This constrains the request level - settings. The default will change to ``gemini-2.5-flash``, - and setting ``thinking_mode`` will not be supported. + Use the most up-to-date non-preview model. + This may constrain certain request level + settings. """ MODEL_UNSPECIFIED = 0 diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/conversation.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/conversation.py index b53d4dd0bd37..a9088330f2de 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/conversation.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/conversation.py @@ -17,6 +17,7 @@ from typing import MutableMapping, MutableSequence +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import proto # type: ignore @@ -25,6 +26,7 @@ manifest={ "Conversation", "CreateConversationRequest", + "UpdateConversationRequest", "GetConversationRequest", "ListConversationsRequest", "ListConversationsResponse", @@ -69,6 +71,9 @@ class Conversation(proto.Message): that can be set by the client to tag a conversation (e.g. to filter conversations for specific surfaces/products). + title (str): + Optional. The display name for the + conversation (max 63 chars). kms_key (str): Optional. Customer managed encryption key (CMEK) to use for encrypting the Conversation resources. Encryption will @@ -78,11 +83,6 @@ class Conversation(proto.Message): projects/{project_id}/locations/{location}/keyRings/{key_ring_name}/cryptoKeys/{key_name}. This field is a member of `oneof`_ ``_kms_key``. - memory_paused (bool): - Optional. Whether memory is paused for this - conversation. - - This field is a member of `oneof`_ ``_memory_paused``. """ name: str = proto.Field( @@ -108,16 +108,15 @@ class Conversation(proto.Message): proto.STRING, number=9, ) + title: str = proto.Field( + proto.STRING, + number=6, + ) kms_key: str = proto.Field( proto.STRING, number=10, optional=True, ) - memory_paused: bool = proto.Field( - proto.BOOL, - number=11, - optional=True, - ) class CreateConversationRequest(proto.Message): @@ -162,6 +161,46 @@ class CreateConversationRequest(proto.Message): ) +class UpdateConversationRequest(proto.Message): + r"""Request for updating a conversation. + + Attributes: + conversation (google.cloud.geminidataanalytics_v1.types.Conversation): + Required. The resource being updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Conversation resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields with non-default values present in the + request will be overwritten. If a wildcard mask is provided, + all fields will be overwritten. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + """ + + conversation: "Conversation" = proto.Field( + proto.MESSAGE, + number=1, + message="Conversation", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + class GetConversationRequest(proto.Message): r"""Request for getting a conversation based on parent and conversation id. diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/data_agent.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/data_agent.py index 726adebd9a31..2ab345473e93 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/data_agent.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/data_agent.py @@ -23,6 +23,7 @@ from google.cloud.geminidataanalytics_v1.types import ( data_analytics_agent as gcg_data_analytics_agent, ) +from google.cloud.geminidataanalytics_v1.types import datasource __protobuf__ = proto.module( package="google.cloud.geminidataanalytics.v1", @@ -92,6 +93,67 @@ class DataAgent(proto.Message): ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. This field is a member of `oneof`_ ``_kms_key``. + bigquery_agent_analytics_enabled (bool): + Optional. Controls whether BigQuery Agent Analytics trace + logging is enabled for the agent. + + BigQuery Agent Analytics is in Preview and is delivered to + enrolled projects only. In a project that is not enrolled + this field is accepted and stored, but no trace rows are + written and no error is returned. + + Trace logging is additionally suppressed for the entire + turn, without error, when any table in the agent's + datasource carries row-level security, column-level security + or policy tags. It is also suppressed when that + determination cannot be made, for example when the caller + lacks permission to list a table's row access policies. + + Trace rows are written only when this is ``true`` and + ``bigquery_agent_analytics_table`` is set. On a BigQuery + agent, enabling this without a table has no effect: no table + is created for the agent and no rows are written. On an + agent whose datasource is not BigQuery, ``CreateDataAgent`` + rejects either field with ``INVALID_ARGUMENT``. + + This setting is independent of the project-level BigQuery + Agent Analytics setting configured through + ``SetAgentOpsObservability``. An agent does not inherit that + setting. + + This field is a member of `oneof`_ ``_bigquery_agent_analytics_enabled``. + bigquery_agent_analytics_table (google.cloud.geminidataanalytics_v1.types.BigQueryTableReference): + Optional. The BigQuery table that BigQuery Agent Analytics + trace rows are written to. Has no effect unless + ``bigquery_agent_analytics_enabled`` is ``true``. The + Preview enrollment described on that field applies here too. + + The trace table is validated when it is set on + ``CreateDataAgent``, or when it is included in the + ``update_mask`` of an ``UpdateDataAgent`` call. The + following are rejected with ``INVALID_ARGUMENT``: + + - The table must belong to the same project as the agent. + - The agent's datasource must be BigQuery. BigQuery Agent + Analytics is not supported for Looker, Looker Studio or + AlloyDB agents. + + These are validated against the agent as sent in the + request. An agent that carries no datasource is not + validated, and an agent switched to a non-BigQuery + datasource is not re-validated; in the latter case no trace + rows are written. + + The destination dataset must already exist and must grant + write access to the project's Gemini Data Analytics service + agent, whose address is + ``service-PROJECT_NUMBER@gcp-sa-geminidataanalytics.iam.gserviceaccount.com`` + (that grant is not performed on your behalf). Without it the + agent answers normally and no trace rows are written. + + Changing the table on an existing agent affects subsequent + turns only. Rows already written to the previous table are + left in place. """ data_analytics_agent: gcg_data_analytics_agent.DataAnalyticsAgent = proto.Field( @@ -142,6 +204,16 @@ class DataAgent(proto.Message): number=14, optional=True, ) + bigquery_agent_analytics_enabled: bool = proto.Field( + proto.BOOL, + number=18, + optional=True, + ) + bigquery_agent_analytics_table: datasource.BigQueryTableReference = proto.Field( + proto.MESSAGE, + number=19, + message=datasource.BigQueryTableReference, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/data_agent_service.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/data_agent_service.py index 1ccc4a3adbb9..e018526dd58d 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/data_agent_service.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/data_agent_service.py @@ -35,6 +35,11 @@ "UpdateDataAgentRequest", "DeleteDataAgentRequest", "OperationMetadata", + "SetAgentOpsObservabilityRequest", + "SetAgentOpsObservabilityResponse", + "SetAgentOpsObservabilityMetadata", + "RetrieveAgentOpsObservabilityRequest", + "RetrieveAgentOpsObservabilityResponse", }, ) @@ -68,6 +73,9 @@ class ListDataAgentsRequest(proto.Message): Optional. If true, the list results will include soft-deleted DataAgents. Defaults to false. + creator_filter (google.cloud.geminidataanalytics_v1.types.ListAccessibleDataAgentsRequest.CreatorFilter): + Optional. Filter for the creator of the + agent. """ parent: str = proto.Field( @@ -94,6 +102,11 @@ class ListDataAgentsRequest(proto.Message): proto.BOOL, number=6, ) + creator_filter: "ListAccessibleDataAgentsRequest.CreatorFilter" = proto.Field( + proto.ENUM, + number=8, + enum="ListAccessibleDataAgentsRequest.CreatorFilter", + ) class ListDataAgentsResponse(proto.Message): @@ -469,4 +482,159 @@ class OperationMetadata(proto.Message): ) +class SetAgentOpsObservabilityRequest(proto.Message): + r"""Request for SetAgentOpsObservability. + + Attributes: + parent (str): + Required. Parent value for + SetAgentOpsObservabilityRequest. Format: + projects/{project}/locations/{location} + telemetry_enabled (bool): + Optional. Whether to enable or disable AgentOps + observability. When update_mask is provided, this field is + ignored unless specified in the mask. + data_source_type (str): + Required. The data source type for which to + set observability settings. Examples: + "bigquery", "looker". + bqaa_enabled (bool): + Optional. Whether BigQuery Agent Analytics is enabled. Note: + An explicit ``update_mask`` containing "bqaa_enabled" is + required to modify this field. If ``update_mask`` is + omitted, this field is ignored and an existing enabled + setting cannot be disabled. + + This is a project-level setting and does not by itself + enable trace logging for any individual agent. Per-agent + trace logging is controlled by + ``DataAgent.bigquery_agent_analytics_enabled`` together with + ``DataAgent.bigquery_agent_analytics_table``; an agent does + not inherit this setting. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten by the update. The fields specified in the + update_mask are relative to the resource. A field will be + overwritten if it is in the mask. + + If the user does not provide a mask, only + ``telemetry_enabled`` will be updated (for backward + compatibility with legacy callers). Note that disabling + BigQuery Agent Analytics (``bqaa_enabled = false``) requires + providing an explicit ``update_mask`` containing + "bqaa_enabled". + + Per AIP-161: + + - The special wildcard value '\*' is supported to update all + fields. + - Field paths should use snake_case, though camelCase + equivalents (``telemetryEnabled``, ``bqaaEnabled``) are + accepted for REST/JSON transcoding compatibility. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + telemetry_enabled: bool = proto.Field( + proto.BOOL, + number=2, + ) + data_source_type: str = proto.Field( + proto.STRING, + number=3, + ) + bqaa_enabled: bool = proto.Field( + proto.BOOL, + number=4, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + + +class SetAgentOpsObservabilityResponse(proto.Message): + r"""Response for SetAgentOpsObservability.""" + + +class SetAgentOpsObservabilityMetadata(proto.Message): + r"""Metadata for SetAgentOpsObservability.""" + + +class RetrieveAgentOpsObservabilityRequest(proto.Message): + r"""Request for RetrieveAgentOpsObservability. + + Attributes: + parent (str): + Required. Parent value for + RetrieveAgentOpsObservabilityRequest. Format: + projects/{project}/locations/{location} + data_source_type (str): + Required. The data source type for which to + retrieve observability settings. Examples: + "bigquery", "looker". + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + data_source_type: str = proto.Field( + proto.STRING, + number=2, + ) + + +class RetrieveAgentOpsObservabilityResponse(proto.Message): + r"""Response for RetrieveAgentOpsObservability. + + Attributes: + telemetry_enabled (bool): + Output only. Whether AgentOps observability + telemetry is enabled. + bigquery_enabled (bool): + Output only. Whether BigQuery API is enabled. + cloud_trace_enabled (bool): + Output only. Whether Cloud Trace API is + enabled. + cloud_monitoring_enabled (bool): + Output only. Whether Cloud Monitoring API is + enabled. + cloud_logging_enabled (bool): + Output only. Whether Cloud Logging API is + enabled. + bqaa_enabled (bool): + Output only. Whether BigQuery Agent Analytics + is enabled. + """ + + telemetry_enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + bigquery_enabled: bool = proto.Field( + proto.BOOL, + number=3, + ) + cloud_trace_enabled: bool = proto.Field( + proto.BOOL, + number=4, + ) + cloud_monitoring_enabled: bool = proto.Field( + proto.BOOL, + number=5, + ) + cloud_logging_enabled: bool = proto.Field( + proto.BOOL, + number=6, + ) + bqaa_enabled: bool = proto.Field( + proto.BOOL, + number=7, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/data_chat_service.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/data_chat_service.py index 11eb63ff0551..eb442e854944 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/data_chat_service.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/data_chat_service.py @@ -224,7 +224,8 @@ class ThinkingMode(proto.Enum): Values: THINKING_MODE_UNSPECIFIED (0): Unspecified thinking mode, agent will use - THINKING mode by default. + THINKING mode by default except for BigQuery + user defaulting to FAST mode by default. FAST (1): Fast mode, answers quickly. THINKING (2): @@ -236,17 +237,16 @@ class ThinkingMode(proto.Enum): THINKING = 2 class Model(proto.Enum): - r"""Model selection for the agent. + r"""Model selection for the agent for BigQuery users. Values: MODEL_UNSPECIFIED (0): - No model specified. The default model will be used. - Currently, this is ``gemini-3.0-flash-preview``. + No model specified. Either preview or non + preview model can be used. LATEST_GA_MODEL (1): - Use the most up-to-date non-preview model. Currently, this - is ``gemini-2.5-flash``. This constrains the request level - settings. The default will change to ``gemini-2.5-flash``, - and setting ``thinking_mode`` will not be supported. + Use the most up-to-date non-preview model. + This may constrain certain request level + settings. """ MODEL_UNSPECIFIED = 0 diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/__init__.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/__init__.py index 7ef18a34785a..b574c0c748e4 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/__init__.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/__init__.py @@ -26,20 +26,24 @@ # https://docs.python.org/3.15/library/sys.html#sys.set_lazy_imports_filter # Older Python versions safely ignore this variable. __lazy_modules__ = { + "google.cloud.geminidataanalytics_v1alpha.services.data_a2a_service", "google.cloud.geminidataanalytics_v1alpha.services.data_agent_service", "google.cloud.geminidataanalytics_v1alpha.services.data_chat_service", "google.cloud.geminidataanalytics_v1alpha.types.agent_context", "google.cloud.geminidataanalytics_v1alpha.types.context", "google.cloud.geminidataanalytics_v1alpha.types.conversation", "google.cloud.geminidataanalytics_v1alpha.types.credentials", + "google.cloud.geminidataanalytics_v1alpha.types.data_a2a_service", "google.cloud.geminidataanalytics_v1alpha.types.data_agent", "google.cloud.geminidataanalytics_v1alpha.types.data_agent_service", "google.cloud.geminidataanalytics_v1alpha.types.data_analytics_agent", "google.cloud.geminidataanalytics_v1alpha.types.data_chat_service", "google.cloud.geminidataanalytics_v1alpha.types.datasource", + "google.cloud.geminidataanalytics_v1alpha.types.usage", } +from .services.data_a2a_service import DataA2AServiceAsyncClient, DataA2AServiceClient from .services.data_agent_service import ( DataAgentServiceAsyncClient, DataAgentServiceClient, @@ -51,14 +55,24 @@ from .types.agent_context import AgentContextReference from .types.context import ( AnalysisOptions, + BigQueryRoutine, + BigQueryRoutineReference, ChartOptions, + Citation, + CitationAnchor, + CitationSource, Context, ConversationOptions, DatasourceOptions, + DynamicField, ExampleQuery, GlossaryTerm, LookerGoldenQuery, LookerQuery, + MatchedQuery, + QueryParameter, + QueryParameterValues, + UserFunctions, ) from .types.conversation import ( Conversation, @@ -67,8 +81,49 @@ GetConversationRequest, ListConversationsRequest, ListConversationsResponse, + UpdateConversationRequest, ) from .types.credentials import Credentials, OAuthCredentials +from .types.data_a2a_service import ( + A2AArtifact, + A2AMessage, + A2ATask, + AgentCapabilities, + AgentCard, + AgentCardSignature, + AgentExtension, + AgentInterface, + AgentProvider, + AgentSkill, + APIKeySecurityScheme, + AuthenticationInfo, + AuthorizationCodeOAuthFlow, + ClientCredentialsOAuthFlow, + DataPart, + FilePart, + GetAgentCardRequest, + HTTPAuthSecurityScheme, + ImplicitOAuthFlow, + MutualTlsSecurityScheme, + OAuth2SecurityScheme, + OAuthFlows, + OpenIdConnectSecurityScheme, + Part, + PasswordOAuthFlow, + PushNotificationConfig, + Role, + Security, + SecurityScheme, + SendMessageConfiguration, + SendMessageRequest, + SendMessageResponse, + StreamResponse, + StringList, + TaskArtifactUpdateEvent, + TaskState, + TaskStatus, + TaskStatusUpdateEvent, +) from .types.data_agent import DataAgent from .types.data_agent_service import ( CreateDataAgentRequest, @@ -79,6 +134,11 @@ ListDataAgentsRequest, ListDataAgentsResponse, OperationMetadata, + RetrieveAgentOpsObservabilityRequest, + RetrieveAgentOpsObservabilityResponse, + SetAgentOpsObservabilityMetadata, + SetAgentOpsObservabilityRequest, + SetAgentOpsObservabilityResponse, UpdateDataAgentRequest, ) from .types.data_analytics_agent import DataAnalyticsAgent @@ -106,6 +166,7 @@ GenerationOptions, ListMessagesRequest, ListMessagesResponse, + LookerSettings, Message, ParameterizedSecureViewParameters, QueryDataContext, @@ -122,6 +183,7 @@ from .types.datasource import ( AlloyDbDatabaseReference, AlloyDbReference, + BigQueryPropertyGraphReference, BigQueryTableReference, BigQueryTableReferences, BigtableDatabaseReference, @@ -145,18 +207,36 @@ StudioDatasourceReference, StudioDatasourceReferences, ) +from .types.usage import TokenUsage __all__ = ( + "DataA2AServiceAsyncClient", "DataAgentServiceAsyncClient", "DataChatServiceAsyncClient", + "A2AArtifact", + "A2AMessage", + "A2ATask", + "APIKeySecurityScheme", + "AgentCapabilities", + "AgentCard", + "AgentCardSignature", "AgentContextReference", + "AgentExtension", + "AgentInterface", + "AgentProvider", + "AgentSkill", "AlloyDbDatabaseReference", "AlloyDbReference", "AnalysisEvent", "AnalysisMessage", "AnalysisOptions", "AnalysisQuery", + "AuthenticationInfo", + "AuthorizationCodeOAuthFlow", "BigQueryJob", + "BigQueryPropertyGraphReference", + "BigQueryRoutine", + "BigQueryRoutineReference", "BigQueryTableReference", "BigQueryTableReferences", "BigtableDatabaseReference", @@ -167,8 +247,12 @@ "ChartQuery", "ChartResult", "ChatRequest", + "Citation", + "CitationAnchor", + "CitationSource", "ClarificationMessage", "ClarificationQuestion", + "ClientCredentialsOAuthFlow", "ClientManagedResourceContext", "CloudSqlDatabaseReference", "CloudSqlReference", @@ -179,6 +263,7 @@ "CreateConversationRequest", "CreateDataAgentRequest", "Credentials", + "DataA2AServiceClient", "DataAgent", "DataAgentContext", "DataAgentServiceClient", @@ -187,6 +272,7 @@ "DataFilter", "DataFilterType", "DataMessage", + "DataPart", "DataQuery", "DataResult", "DatabaseTableReference", @@ -195,17 +281,22 @@ "DatasourceReferences", "DeleteConversationRequest", "DeleteDataAgentRequest", + "DynamicField", "ErrorMessage", "ExampleQueries", "ExampleQuery", "ExecutedQueryResult", "Field", + "FilePart", "FirestoreDatabaseReference", "FirestoreReference", "GenerationOptions", + "GetAgentCardRequest", "GetConversationRequest", "GetDataAgentRequest", "GlossaryTerm", + "HTTPAuthSecurityScheme", + "ImplicitOAuthFlow", "ListAccessibleDataAgentsRequest", "ListAccessibleDataAgentsResponse", "ListConversationsRequest", @@ -218,26 +309,57 @@ "LookerExploreReferences", "LookerGoldenQuery", "LookerQuery", + "LookerSettings", + "MatchedQuery", "Message", + "MutualTlsSecurityScheme", + "OAuth2SecurityScheme", "OAuthCredentials", + "OAuthFlows", + "OpenIdConnectSecurityScheme", "OperationMetadata", "ParameterizedSecureViewParameters", + "Part", + "PasswordOAuthFlow", "PrivateLookerInstanceInfo", + "PushNotificationConfig", "QueryDataContext", "QueryDataRequest", "QueryDataResponse", + "QueryParameter", + "QueryParameterValues", + "RetrieveAgentOpsObservabilityRequest", + "RetrieveAgentOpsObservabilityResponse", + "Role", "Schema", "SchemaMessage", "SchemaQuery", "SchemaResult", + "Security", + "SecurityScheme", + "SendMessageConfiguration", + "SendMessageRequest", + "SendMessageResponse", + "SetAgentOpsObservabilityMetadata", + "SetAgentOpsObservabilityRequest", + "SetAgentOpsObservabilityResponse", "SpannerDatabaseReference", "SpannerReference", "StorageMessage", + "StreamResponse", + "StringList", "StudioDatasourceReference", "StudioDatasourceReferences", "SystemMessage", + "TaskArtifactUpdateEvent", + "TaskState", + "TaskStatus", + "TaskStatusUpdateEvent", "TextMessage", + "TokenUsage", + "UpdateConversationRequest", "UpdateDataAgentRequest", + "UserFunctions", "UserMessage", ) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/gapic_metadata.json b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/gapic_metadata.json index 3d2027293d05..bf008133d2e2 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/gapic_metadata.json +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/gapic_metadata.json @@ -5,6 +5,70 @@ "protoPackage": "google.cloud.geminidataanalytics.v1alpha", "schema": "1.0", "services": { + "DataA2AService": { + "clients": { + "grpc": { + "libraryClient": "DataA2AServiceClient", + "rpcs": { + "GetAgentCard": { + "methods": [ + "get_agent_card" + ] + }, + "SendMessage": { + "methods": [ + "send_message" + ] + }, + "SendStreamingMessage": { + "methods": [ + "send_streaming_message" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DataA2AServiceAsyncClient", + "rpcs": { + "GetAgentCard": { + "methods": [ + "get_agent_card" + ] + }, + "SendMessage": { + "methods": [ + "send_message" + ] + }, + "SendStreamingMessage": { + "methods": [ + "send_streaming_message" + ] + } + } + }, + "rest": { + "libraryClient": "DataA2AServiceClient", + "rpcs": { + "GetAgentCard": { + "methods": [ + "get_agent_card" + ] + }, + "SendMessage": { + "methods": [ + "send_message" + ] + }, + "SendStreamingMessage": { + "methods": [ + "send_streaming_message" + ] + } + } + } + } + }, "DataAgentService": { "clients": { "grpc": { @@ -50,6 +114,16 @@ "list_data_agents" ] }, + "RetrieveAgentOpsObservability": { + "methods": [ + "retrieve_agent_ops_observability" + ] + }, + "SetAgentOpsObservability": { + "methods": [ + "set_agent_ops_observability" + ] + }, "SetIamPolicy": { "methods": [ "set_iam_policy" @@ -110,6 +184,16 @@ "list_data_agents" ] }, + "RetrieveAgentOpsObservability": { + "methods": [ + "retrieve_agent_ops_observability" + ] + }, + "SetAgentOpsObservability": { + "methods": [ + "set_agent_ops_observability" + ] + }, "SetIamPolicy": { "methods": [ "set_iam_policy" @@ -170,6 +254,16 @@ "list_data_agents" ] }, + "RetrieveAgentOpsObservability": { + "methods": [ + "retrieve_agent_ops_observability" + ] + }, + "SetAgentOpsObservability": { + "methods": [ + "set_agent_ops_observability" + ] + }, "SetIamPolicy": { "methods": [ "set_iam_policy" @@ -228,6 +322,11 @@ "methods": [ "query_data" ] + }, + "UpdateConversation": { + "methods": [ + "update_conversation" + ] } } }, @@ -268,6 +367,11 @@ "methods": [ "query_data" ] + }, + "UpdateConversation": { + "methods": [ + "update_conversation" + ] } } }, @@ -308,6 +412,11 @@ "methods": [ "query_data" ] + }, + "UpdateConversation": { + "methods": [ + "update_conversation" + ] } } } diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/__init__.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/__init__.py new file mode 100644 index 000000000000..5c4c8745b6ac --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import DataA2AServiceAsyncClient +from .client import DataA2AServiceClient + +__all__ = ( + "DataA2AServiceClient", + "DataA2AServiceAsyncClient", +) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/async_client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/async_client.py new file mode 100644 index 000000000000..1ce4cb839ec6 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/async_client.py @@ -0,0 +1,1017 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + AsyncIterable, + Awaitable, + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.geminidataanalytics_v1alpha import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.geminidataanalytics_v1alpha.types import data_a2a_service + +from .client import DataA2AServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, DataA2AServiceTransport +from .transports.grpc_asyncio import DataA2AServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class DataA2AServiceAsyncClient: + """DataA2AService defines the Agent-to-Agent (A2A) protocol + service for Gemini Data Analytics. + """ + + _client: DataA2AServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = DataA2AServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DataA2AServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = DataA2AServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = DataA2AServiceClient._DEFAULT_UNIVERSE + + common_billing_account_path = staticmethod( + DataA2AServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + DataA2AServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(DataA2AServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + DataA2AServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + DataA2AServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + DataA2AServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(DataA2AServiceClient.common_project_path) + parse_common_project_path = staticmethod( + DataA2AServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(DataA2AServiceClient.common_location_path) + parse_common_location_path = staticmethod( + DataA2AServiceClient.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: + DataA2AServiceAsyncClient: The constructed client. + """ + sa_info_func = ( + DataA2AServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(DataA2AServiceAsyncClient, info, *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: + DataA2AServiceAsyncClient: The constructed client. + """ + sa_file_func = ( + DataA2AServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(DataA2AServiceAsyncClient, filename, *args, **kwargs) + + 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 DataA2AServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DataA2AServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DataA2AServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = DataA2AServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, DataA2AServiceTransport, Callable[..., DataA2AServiceTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the data a2a service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,DataA2AServiceTransport,Callable[..., DataA2AServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the DataA2AServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = DataA2AServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.geminidataanalytics_v1alpha.DataA2AServiceAsyncClient`.", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "credentialsType": None, + }, + ) + + async def send_message( + self, + request: Optional[Union[data_a2a_service.SendMessageRequest, dict]] = None, + *, + tenant: Optional[str] = None, + message: Optional[data_a2a_service.A2AMessage] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_a2a_service.SendMessageResponse: + r"""Send a message to the agent. This is a blocking call + that will return the task once it is completed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1alpha + + async def sample_send_message(): + # Create a client + client = geminidataanalytics_v1alpha.DataA2AServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.SendMessageRequest( + ) + + # Make the request + response = await client.send_message(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.geminidataanalytics_v1alpha.types.SendMessageRequest, dict]]): + The request object. Request message for SendMessage and + SendStreamingMessage. + tenant (:class:`str`): + Optional. Optional tenant, provided + as a path parameter. + + This corresponds to the ``tenant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message (:class:`google.cloud.geminidataanalytics_v1alpha.types.A2AMessage`): + Required. The message to send to the + agent. + + This corresponds to the ``message`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1alpha.types.SendMessageResponse: + Response message for SendMessage. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [tenant, message] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, data_a2a_service.SendMessageRequest): + request = data_a2a_service.SendMessageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tenant is not None: + request.tenant = tenant + if message is not None: + request.message = message + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.send_message + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("tenant", request.tenant),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def send_streaming_message( + self, + request: Optional[Union[data_a2a_service.SendMessageRequest, dict]] = None, + *, + tenant: Optional[str] = None, + message: Optional[data_a2a_service.A2AMessage] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Awaitable[AsyncIterable[data_a2a_service.StreamResponse]]: + r"""SendStreamingMessage is a streaming call that will + return a stream of task update events until the Task is + in an interrupted or terminal state. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1alpha + + async def sample_send_streaming_message(): + # Create a client + client = geminidataanalytics_v1alpha.DataA2AServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.SendMessageRequest( + ) + + # Make the request + stream = await client.send_streaming_message(request=request) + + # Handle the response + async for response in stream: + print(response) + + Args: + request (Optional[Union[google.cloud.geminidataanalytics_v1alpha.types.SendMessageRequest, dict]]): + The request object. Request message for SendMessage and + SendStreamingMessage. + tenant (:class:`str`): + Optional. Optional tenant, provided + as a path parameter. + + This corresponds to the ``tenant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message (:class:`google.cloud.geminidataanalytics_v1alpha.types.A2AMessage`): + Required. The message to send to the + agent. + + This corresponds to the ``message`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + AsyncIterable[google.cloud.geminidataanalytics_v1alpha.types.StreamResponse]: + The stream response for a message. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [tenant, message] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, data_a2a_service.SendMessageRequest): + request = data_a2a_service.SendMessageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tenant is not None: + request.tenant = tenant + if message is not None: + request.message = message + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.send_streaming_message + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("tenant", request.tenant),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_agent_card( + self, + request: Optional[Union[data_a2a_service.GetAgentCardRequest, dict]] = None, + *, + tenant: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_a2a_service.AgentCard: + r"""GetAgentCard returns the agent card for the agent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1alpha + + async def sample_get_agent_card(): + # Create a client + client = geminidataanalytics_v1alpha.DataA2AServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.GetAgentCardRequest( + ) + + # Make the request + response = await client.get_agent_card(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.geminidataanalytics_v1alpha.types.GetAgentCardRequest, dict]]): + The request object. Request message for GetAgentCard. + tenant (:class:`str`): + Optional. Optional tenant, provided + as a path parameter. + + This corresponds to the ``tenant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1alpha.types.AgentCard: + AgentCard conveys key information + about an agent. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [tenant] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, data_a2a_service.GetAgentCardRequest): + request = data_a2a_service.GetAgentCardRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tenant is not None: + request.tenant = tenant + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_agent_card + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("tenant", request.tenant),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "DataA2AServiceAsyncClient": + 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__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("DataA2AServiceAsyncClient",) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/client.py new file mode 100644 index 000000000000..7b6e4b6a825a --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/client.py @@ -0,0 +1,1306 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Iterable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +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.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.geminidataanalytics_v1alpha import gapic_version as package_version +from google.cloud.geminidataanalytics_v1alpha._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.geminidataanalytics_v1alpha.types import data_a2a_service + +from .transports.base import DEFAULT_CLIENT_INFO, DataA2AServiceTransport +from .transports.grpc import DataA2AServiceGrpcTransport +from .transports.grpc_asyncio import DataA2AServiceGrpcAsyncIOTransport +from .transports.rest import DataA2AServiceRestTransport + + +class DataA2AServiceClientMeta(type): + """Metaclass for the DataA2AService 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[DataA2AServiceTransport]] + _transport_registry["grpc"] = DataA2AServiceGrpcTransport + _transport_registry["grpc_asyncio"] = DataA2AServiceGrpcAsyncIOTransport + _transport_registry["rest"] = DataA2AServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[DataA2AServiceTransport]: + """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 DataA2AServiceClient(metaclass=DataA2AServiceClientMeta): + """DataA2AService defines the Agent-to-Agent (A2A) protocol + service for Gemini Data Analytics. + """ + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "geminidataanalytics.googleapis.com" + DEFAULT_MTLS_ENDPOINT = get_default_mtls_endpoint(DEFAULT_ENDPOINT) + + _DEFAULT_ENDPOINT_TEMPLATE = "geminidataanalytics.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DataA2AServiceClient: 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: + DataA2AServiceClient: 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) -> DataA2AServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DataA2AServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = should_use_client_cert() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + 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: + 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 # type: ignore + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, DataA2AServiceTransport, Callable[..., DataA2AServiceTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the data a2a service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,DataA2AServiceTransport,Callable[..., DataA2AServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the DataA2AServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = DataA2AServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=DataA2AServiceClient._DEFAULT_UNIVERSE, + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, DataA2AServiceTransport) + if transport_provided: + # transport is a DataA2AServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(DataA2AServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=DataA2AServiceClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=DataA2AServiceClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=DataA2AServiceClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[DataA2AServiceTransport], Callable[..., DataA2AServiceTransport] + ] = ( + DataA2AServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., DataA2AServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.geminidataanalytics_v1alpha.DataA2AServiceClient`.", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "credentialsType": None, + }, + ) + + def send_message( + self, + request: Optional[Union[data_a2a_service.SendMessageRequest, dict]] = None, + *, + tenant: Optional[str] = None, + message: Optional[data_a2a_service.A2AMessage] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_a2a_service.SendMessageResponse: + r"""Send a message to the agent. This is a blocking call + that will return the task once it is completed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1alpha + + def sample_send_message(): + # Create a client + client = geminidataanalytics_v1alpha.DataA2AServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.SendMessageRequest( + ) + + # Make the request + response = client.send_message(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.geminidataanalytics_v1alpha.types.SendMessageRequest, dict]): + The request object. Request message for SendMessage and + SendStreamingMessage. + tenant (str): + Optional. Optional tenant, provided + as a path parameter. + + This corresponds to the ``tenant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message (google.cloud.geminidataanalytics_v1alpha.types.A2AMessage): + Required. The message to send to the + agent. + + This corresponds to the ``message`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1alpha.types.SendMessageResponse: + Response message for SendMessage. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [tenant, message] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, data_a2a_service.SendMessageRequest): + request = data_a2a_service.SendMessageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tenant is not None: + request.tenant = tenant + if message is not None: + request.message = message + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.send_message] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("tenant", request.tenant),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def send_streaming_message( + self, + request: Optional[Union[data_a2a_service.SendMessageRequest, dict]] = None, + *, + tenant: Optional[str] = None, + message: Optional[data_a2a_service.A2AMessage] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[data_a2a_service.StreamResponse]: + r"""SendStreamingMessage is a streaming call that will + return a stream of task update events until the Task is + in an interrupted or terminal state. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1alpha + + def sample_send_streaming_message(): + # Create a client + client = geminidataanalytics_v1alpha.DataA2AServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.SendMessageRequest( + ) + + # Make the request + stream = client.send_streaming_message(request=request) + + # Handle the response + for response in stream: + print(response) + + Args: + request (Union[google.cloud.geminidataanalytics_v1alpha.types.SendMessageRequest, dict]): + The request object. Request message for SendMessage and + SendStreamingMessage. + tenant (str): + Optional. Optional tenant, provided + as a path parameter. + + This corresponds to the ``tenant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message (google.cloud.geminidataanalytics_v1alpha.types.A2AMessage): + Required. The message to send to the + agent. + + This corresponds to the ``message`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + Iterable[google.cloud.geminidataanalytics_v1alpha.types.StreamResponse]: + The stream response for a message. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [tenant, message] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, data_a2a_service.SendMessageRequest): + request = data_a2a_service.SendMessageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tenant is not None: + request.tenant = tenant + if message is not None: + request.message = message + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.send_streaming_message] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("tenant", request.tenant),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_agent_card( + self, + request: Optional[Union[data_a2a_service.GetAgentCardRequest, dict]] = None, + *, + tenant: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_a2a_service.AgentCard: + r"""GetAgentCard returns the agent card for the agent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1alpha + + def sample_get_agent_card(): + # Create a client + client = geminidataanalytics_v1alpha.DataA2AServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.GetAgentCardRequest( + ) + + # Make the request + response = client.get_agent_card(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.geminidataanalytics_v1alpha.types.GetAgentCardRequest, dict]): + The request object. Request message for GetAgentCard. + tenant (str): + Optional. Optional tenant, provided + as a path parameter. + + This corresponds to the ``tenant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1alpha.types.AgentCard: + AgentCard conveys key information + about an agent. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [tenant] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, data_a2a_service.GetAgentCardRequest): + request = data_a2a_service.GetAgentCardRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tenant is not None: + request.tenant = tenant + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_agent_card] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("tenant", request.tenant),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "DataA2AServiceClient": + 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[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("DataA2AServiceClient",) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/README.rst b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/README.rst new file mode 100644 index 000000000000..991eb507e49d --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``DataA2AServiceTransport`` is the ABC for all transports. + +- public child ``DataA2AServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``DataA2AServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseDataA2AServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``DataA2AServiceRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/__init__.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/__init__.py new file mode 100644 index 000000000000..d9bac7b888fc --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 DataA2AServiceTransport +from .grpc import DataA2AServiceGrpcTransport +from .grpc_asyncio import DataA2AServiceGrpcAsyncIOTransport +from .rest import DataA2AServiceRestInterceptor, DataA2AServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DataA2AServiceTransport]] +_transport_registry["grpc"] = DataA2AServiceGrpcTransport +_transport_registry["grpc_asyncio"] = DataA2AServiceGrpcAsyncIOTransport +_transport_registry["rest"] = DataA2AServiceRestTransport + +__all__ = ( + "DataA2AServiceTransport", + "DataA2AServiceGrpcTransport", + "DataA2AServiceGrpcAsyncIOTransport", + "DataA2AServiceRestTransport", + "DataA2AServiceRestInterceptor", +) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/base.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/base.py new file mode 100644 index 000000000000..9ab966ae551f --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/base.py @@ -0,0 +1,298 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +import google.api_core +import google.auth # type: ignore +import google.protobuf +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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.geminidataanalytics_v1alpha import gapic_version as package_version +from google.cloud.geminidataanalytics_v1alpha.types import data_a2a_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class DataA2AServiceTransport(abc.ABC): + """Abstract transport class for DataA2AService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "geminidataanalytics.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'geminidataanalytics.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.send_message: gapic_v1.method.wrap_method( + self.send_message, + default_timeout=None, + client_info=client_info, + ), + self.send_streaming_message: gapic_v1.method.wrap_method( + self.send_streaming_message, + default_timeout=None, + client_info=client_info, + ), + self.get_agent_card: gapic_v1.method.wrap_method( + self.get_agent_card, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def send_message( + self, + ) -> Callable[ + [data_a2a_service.SendMessageRequest], + Union[ + data_a2a_service.SendMessageResponse, + Awaitable[data_a2a_service.SendMessageResponse], + ], + ]: + raise NotImplementedError() + + @property + def send_streaming_message( + self, + ) -> Callable[ + [data_a2a_service.SendMessageRequest], + Union[ + data_a2a_service.StreamResponse, Awaitable[data_a2a_service.StreamResponse] + ], + ]: + raise NotImplementedError() + + @property + def get_agent_card( + self, + ) -> Callable[ + [data_a2a_service.GetAgentCardRequest], + Union[data_a2a_service.AgentCard, Awaitable[data_a2a_service.AgentCard]], + ]: + 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 get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("DataA2AServiceTransport",) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/grpc.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/grpc.py new file mode 100644 index 000000000000..83559b6501e8 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/grpc.py @@ -0,0 +1,530 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.geminidataanalytics_v1alpha.types import data_a2a_service + +from .base import DEFAULT_CLIENT_INFO, DataA2AServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class DataA2AServiceGrpcTransport(DataA2AServiceTransport): + """gRPC backend transport for DataA2AService. + + DataA2AService defines the Agent-to-Agent (A2A) protocol + service for Gemini Data Analytics. + + 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 = "geminidataanalytics.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'geminidataanalytics.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "geminidataanalytics.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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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 send_message( + self, + ) -> Callable[ + [data_a2a_service.SendMessageRequest], data_a2a_service.SendMessageResponse + ]: + r"""Return a callable for the send message method over gRPC. + + Send a message to the agent. This is a blocking call + that will return the task once it is completed. + + Returns: + Callable[[~.SendMessageRequest], + ~.SendMessageResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "send_message" not in self._stubs: + self._stubs["send_message"] = self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1alpha.DataA2AService/SendMessage", + request_serializer=data_a2a_service.SendMessageRequest.serialize, + response_deserializer=data_a2a_service.SendMessageResponse.deserialize, + ) + return self._stubs["send_message"] + + @property + def send_streaming_message( + self, + ) -> Callable[ + [data_a2a_service.SendMessageRequest], data_a2a_service.StreamResponse + ]: + r"""Return a callable for the send streaming message method over gRPC. + + SendStreamingMessage is a streaming call that will + return a stream of task update events until the Task is + in an interrupted or terminal state. + + Returns: + Callable[[~.SendMessageRequest], + ~.StreamResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "send_streaming_message" not in self._stubs: + self._stubs["send_streaming_message"] = self._logged_channel.unary_stream( + "/google.cloud.geminidataanalytics.v1alpha.DataA2AService/SendStreamingMessage", + request_serializer=data_a2a_service.SendMessageRequest.serialize, + response_deserializer=data_a2a_service.StreamResponse.deserialize, + ) + return self._stubs["send_streaming_message"] + + @property + def get_agent_card( + self, + ) -> Callable[[data_a2a_service.GetAgentCardRequest], data_a2a_service.AgentCard]: + r"""Return a callable for the get agent card method over gRPC. + + GetAgentCard returns the agent card for the agent. + + Returns: + Callable[[~.GetAgentCardRequest], + ~.AgentCard]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent_card" not in self._stubs: + self._stubs["get_agent_card"] = self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1alpha.DataA2AService/GetAgentCard", + request_serializer=data_a2a_service.GetAgentCardRequest.serialize, + response_deserializer=data_a2a_service.AgentCard.deserialize, + ) + return self._stubs["get_agent_card"] + + def close(self): + self._logged_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._logged_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._logged_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._logged_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._logged_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 list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("DataA2AServiceGrpcTransport",) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/grpc_asyncio.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..7111905fcc83 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/grpc_asyncio.py @@ -0,0 +1,597 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.geminidataanalytics_v1alpha.types import data_a2a_service + +from .base import DEFAULT_CLIENT_INFO, DataA2AServiceTransport +from .grpc import DataA2AServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class DataA2AServiceGrpcAsyncIOTransport(DataA2AServiceTransport): + """gRPC AsyncIO backend transport for DataA2AService. + + DataA2AService defines the Agent-to-Agent (A2A) protocol + service for Gemini Data Analytics. + + 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 = "geminidataanalytics.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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + 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 = "geminidataanalytics.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'geminidataanalytics.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_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 send_message( + self, + ) -> Callable[ + [data_a2a_service.SendMessageRequest], + Awaitable[data_a2a_service.SendMessageResponse], + ]: + r"""Return a callable for the send message method over gRPC. + + Send a message to the agent. This is a blocking call + that will return the task once it is completed. + + Returns: + Callable[[~.SendMessageRequest], + Awaitable[~.SendMessageResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "send_message" not in self._stubs: + self._stubs["send_message"] = self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1alpha.DataA2AService/SendMessage", + request_serializer=data_a2a_service.SendMessageRequest.serialize, + response_deserializer=data_a2a_service.SendMessageResponse.deserialize, + ) + return self._stubs["send_message"] + + @property + def send_streaming_message( + self, + ) -> Callable[ + [data_a2a_service.SendMessageRequest], + Awaitable[data_a2a_service.StreamResponse], + ]: + r"""Return a callable for the send streaming message method over gRPC. + + SendStreamingMessage is a streaming call that will + return a stream of task update events until the Task is + in an interrupted or terminal state. + + Returns: + Callable[[~.SendMessageRequest], + Awaitable[~.StreamResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "send_streaming_message" not in self._stubs: + self._stubs["send_streaming_message"] = self._logged_channel.unary_stream( + "/google.cloud.geminidataanalytics.v1alpha.DataA2AService/SendStreamingMessage", + request_serializer=data_a2a_service.SendMessageRequest.serialize, + response_deserializer=data_a2a_service.StreamResponse.deserialize, + ) + return self._stubs["send_streaming_message"] + + @property + def get_agent_card( + self, + ) -> Callable[ + [data_a2a_service.GetAgentCardRequest], Awaitable[data_a2a_service.AgentCard] + ]: + r"""Return a callable for the get agent card method over gRPC. + + GetAgentCard returns the agent card for the agent. + + Returns: + Callable[[~.GetAgentCardRequest], + Awaitable[~.AgentCard]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent_card" not in self._stubs: + self._stubs["get_agent_card"] = self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1alpha.DataA2AService/GetAgentCard", + request_serializer=data_a2a_service.GetAgentCardRequest.serialize, + response_deserializer=data_a2a_service.AgentCard.deserialize, + ) + return self._stubs["get_agent_card"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.send_message: self._wrap_method( + self.send_message, + default_timeout=None, + client_info=client_info, + ), + self.send_streaming_message: self._wrap_method( + self.send_streaming_message, + default_timeout=None, + client_info=client_info, + ), + self.get_agent_card: self._wrap_method( + self.get_agent_card, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @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._logged_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._logged_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._logged_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._logged_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 list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ("DataA2AServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/rest.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/rest.py new file mode 100644 index 000000000000..4723aa3b3aa1 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/rest.py @@ -0,0 +1,1765 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.geminidataanalytics_v1alpha._compat import transcode_request +from google.cloud.geminidataanalytics_v1alpha.types import data_a2a_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseDataA2AServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class DataA2AServiceRestInterceptor: + """Interceptor for DataA2AService. + + 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 DataA2AServiceRestTransport. + + .. code-block:: python + class MyCustomDataA2AServiceInterceptor(DataA2AServiceRestInterceptor): + def pre_get_agent_card(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_agent_card(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_send_message(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_send_message(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_send_streaming_message(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_send_streaming_message(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DataA2AServiceRestTransport(interceptor=MyCustomDataA2AServiceInterceptor()) + client = DataA2AServiceClient(transport=transport) + + + """ + + def pre_get_agent_card( + self, + request: data_a2a_service.GetAgentCardRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_a2a_service.GetAgentCardRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_agent_card + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataA2AService server. + """ + return request, metadata + + def post_get_agent_card( + self, response: data_a2a_service.AgentCard + ) -> data_a2a_service.AgentCard: + """Post-rpc interceptor for get_agent_card + + DEPRECATED. Please use the `post_get_agent_card_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DataA2AService server but before + it is returned to user code. This `post_get_agent_card` interceptor runs + before the `post_get_agent_card_with_metadata` interceptor. + """ + return response + + def post_get_agent_card_with_metadata( + self, + response: data_a2a_service.AgentCard, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[data_a2a_service.AgentCard, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_agent_card + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DataA2AService server but before it is returned to user code. + + We recommend only using this `post_get_agent_card_with_metadata` + interceptor in new development instead of the `post_get_agent_card` interceptor. + When both interceptors are used, this `post_get_agent_card_with_metadata` interceptor runs after the + `post_get_agent_card` interceptor. The (possibly modified) response returned by + `post_get_agent_card` will be passed to + `post_get_agent_card_with_metadata`. + """ + return response, metadata + + def pre_send_message( + self, + request: data_a2a_service.SendMessageRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_a2a_service.SendMessageRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for send_message + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataA2AService server. + """ + return request, metadata + + def post_send_message( + self, response: data_a2a_service.SendMessageResponse + ) -> data_a2a_service.SendMessageResponse: + """Post-rpc interceptor for send_message + + DEPRECATED. Please use the `post_send_message_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DataA2AService server but before + it is returned to user code. This `post_send_message` interceptor runs + before the `post_send_message_with_metadata` interceptor. + """ + return response + + def post_send_message_with_metadata( + self, + response: data_a2a_service.SendMessageResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_a2a_service.SendMessageResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for send_message + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DataA2AService server but before it is returned to user code. + + We recommend only using this `post_send_message_with_metadata` + interceptor in new development instead of the `post_send_message` interceptor. + When both interceptors are used, this `post_send_message_with_metadata` interceptor runs after the + `post_send_message` interceptor. The (possibly modified) response returned by + `post_send_message` will be passed to + `post_send_message_with_metadata`. + """ + return response, metadata + + def pre_send_streaming_message( + self, + request: data_a2a_service.SendMessageRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_a2a_service.SendMessageRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for send_streaming_message + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataA2AService server. + """ + return request, metadata + + def post_send_streaming_message( + self, response: rest_streaming.ResponseIterator + ) -> rest_streaming.ResponseIterator: + """Post-rpc interceptor for send_streaming_message + + DEPRECATED. Please use the `post_send_streaming_message_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DataA2AService server but before + it is returned to user code. This `post_send_streaming_message` interceptor runs + before the `post_send_streaming_message_with_metadata` interceptor. + """ + return response + + def post_send_streaming_message_with_metadata( + self, + response: rest_streaming.ResponseIterator, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + rest_streaming.ResponseIterator, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for send_streaming_message + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DataA2AService server but before it is returned to user code. + + We recommend only using this `post_send_streaming_message_with_metadata` + interceptor in new development instead of the `post_send_streaming_message` interceptor. + When both interceptors are used, this `post_send_streaming_message_with_metadata` interceptor runs after the + `post_send_streaming_message` interceptor. The (possibly modified) response returned by + `post_send_streaming_message` will be passed to + `post_send_streaming_message_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataA2AService server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the DataA2AService server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataA2AService server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the DataA2AService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataA2AService 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 DataA2AService server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataA2AService 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 DataA2AService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataA2AService 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 DataA2AService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataA2AService 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 DataA2AService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DataA2AServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DataA2AServiceRestInterceptor + + +class DataA2AServiceRestTransport(_BaseDataA2AServiceRestTransport): + """REST backend synchronous transport for DataA2AService. + + DataA2AService defines the Agent-to-Agent (A2A) protocol + service for Gemini Data Analytics. + + 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 = "geminidataanalytics.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[DataA2AServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'geminidataanalytics.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + 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. + interceptor (Optional[DataA2AServiceRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DataA2AServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetAgentCard( + _BaseDataA2AServiceRestTransport._BaseGetAgentCard, DataA2AServiceRestStub + ): + def __hash__(self): + return hash("DataA2AServiceRestTransport.GetAgentCard") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: data_a2a_service.GetAgentCardRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_a2a_service.AgentCard: + r"""Call the get agent card method over HTTP. + + Args: + request (~.data_a2a_service.GetAgentCardRequest): + The request object. Request message for GetAgentCard. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.data_a2a_service.AgentCard: + AgentCard conveys key information + about an agent. + + """ + + http_options = ( + _BaseDataA2AServiceRestTransport._BaseGetAgentCard._get_http_options() + ) + request, metadata = self._interceptor.pre_get_agent_card(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataA2AServiceRestTransport._BaseGetAgentCard, + "_BaseGetAgentCard__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1alpha.DataA2AServiceClient.GetAgentCard", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": "GetAgentCard", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataA2AServiceRestTransport._GetAgentCard._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = data_a2a_service.AgentCard() + pb_resp = data_a2a_service.AgentCard.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_agent_card(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_agent_card_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = data_a2a_service.AgentCard.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1alpha.DataA2AServiceClient.get_agent_card", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": "GetAgentCard", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SendMessage( + _BaseDataA2AServiceRestTransport._BaseSendMessage, DataA2AServiceRestStub + ): + def __hash__(self): + return hash("DataA2AServiceRestTransport.SendMessage") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: data_a2a_service.SendMessageRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_a2a_service.SendMessageResponse: + r"""Call the send message method over HTTP. + + Args: + request (~.data_a2a_service.SendMessageRequest): + The request object. Request message for SendMessage and + SendStreamingMessage. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.data_a2a_service.SendMessageResponse: + Response message for SendMessage. + """ + + http_options = ( + _BaseDataA2AServiceRestTransport._BaseSendMessage._get_http_options() + ) + request, metadata = self._interceptor.pre_send_message(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataA2AServiceRestTransport._BaseSendMessage, + "_BaseSendMessage__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1alpha.DataA2AServiceClient.SendMessage", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": "SendMessage", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataA2AServiceRestTransport._SendMessage._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = data_a2a_service.SendMessageResponse() + pb_resp = data_a2a_service.SendMessageResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_send_message(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_send_message_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = data_a2a_service.SendMessageResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1alpha.DataA2AServiceClient.send_message", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": "SendMessage", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SendStreamingMessage( + _BaseDataA2AServiceRestTransport._BaseSendStreamingMessage, + DataA2AServiceRestStub, + ): + def __hash__(self): + return hash("DataA2AServiceRestTransport.SendStreamingMessage") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + stream=True, + ) + return response + + def __call__( + self, + request: data_a2a_service.SendMessageRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> rest_streaming.ResponseIterator: + r"""Call the send streaming message method over HTTP. + + Args: + request (~.data_a2a_service.SendMessageRequest): + The request object. Request message for SendMessage and + SendStreamingMessage. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.data_a2a_service.StreamResponse: + The stream response for a message. + """ + + http_options = _BaseDataA2AServiceRestTransport._BaseSendStreamingMessage._get_http_options() + request, metadata = self._interceptor.pre_send_streaming_message( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataA2AServiceRestTransport._BaseSendStreamingMessage, + "_BaseSendStreamingMessage__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1alpha.DataA2AServiceClient.SendStreamingMessage", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": "SendStreamingMessage", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataA2AServiceRestTransport._SendStreamingMessage._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = rest_streaming.ResponseIterator( + response, data_a2a_service.StreamResponse + ) + + resp = self._interceptor.post_send_streaming_message(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_send_streaming_message_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + http_response = { + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1alpha.DataA2AServiceClient.send_streaming_message", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": "SendStreamingMessage", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_agent_card( + self, + ) -> Callable[[data_a2a_service.GetAgentCardRequest], data_a2a_service.AgentCard]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAgentCard(self._session, self._host, self._interceptor) # type: ignore + + @property + def send_message( + self, + ) -> Callable[ + [data_a2a_service.SendMessageRequest], data_a2a_service.SendMessageResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SendMessage(self._session, self._host, self._interceptor) # type: ignore + + @property + def send_streaming_message( + self, + ) -> Callable[ + [data_a2a_service.SendMessageRequest], data_a2a_service.StreamResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SendStreamingMessage(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation( + _BaseDataA2AServiceRestTransport._BaseGetLocation, DataA2AServiceRestStub + ): + def __hash__(self): + return hash("DataA2AServiceRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = ( + _BaseDataA2AServiceRestTransport._BaseGetLocation._get_http_options() + ) + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataA2AServiceRestTransport._BaseGetLocation, + "_BaseGetLocation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1alpha.DataA2AServiceClient.GetLocation", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataA2AServiceRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1alpha.DataA2AServiceAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations( + _BaseDataA2AServiceRestTransport._BaseListLocations, DataA2AServiceRestStub + ): + def __hash__(self): + return hash("DataA2AServiceRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = ( + _BaseDataA2AServiceRestTransport._BaseListLocations._get_http_options() + ) + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataA2AServiceRestTransport._BaseListLocations, + "_BaseListLocations__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1alpha.DataA2AServiceClient.ListLocations", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataA2AServiceRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1alpha.DataA2AServiceAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseDataA2AServiceRestTransport._BaseCancelOperation, DataA2AServiceRestStub + ): + def __hash__(self): + return hash("DataA2AServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseDataA2AServiceRestTransport._BaseCancelOperation._get_http_options() + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataA2AServiceRestTransport._BaseCancelOperation, + "_BaseCancelOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1alpha.DataA2AServiceClient.CancelOperation", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataA2AServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation( + _BaseDataA2AServiceRestTransport._BaseDeleteOperation, DataA2AServiceRestStub + ): + def __hash__(self): + return hash("DataA2AServiceRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseDataA2AServiceRestTransport._BaseDeleteOperation._get_http_options() + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataA2AServiceRestTransport._BaseDeleteOperation, + "_BaseDeleteOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1alpha.DataA2AServiceClient.DeleteOperation", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataA2AServiceRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseDataA2AServiceRestTransport._BaseGetOperation, DataA2AServiceRestStub + ): + def __hash__(self): + return hash("DataA2AServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseDataA2AServiceRestTransport._BaseGetOperation._get_http_options() + ) + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataA2AServiceRestTransport._BaseGetOperation, + "_BaseGetOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1alpha.DataA2AServiceClient.GetOperation", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataA2AServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1alpha.DataA2AServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseDataA2AServiceRestTransport._BaseListOperations, DataA2AServiceRestStub + ): + def __hash__(self): + return hash("DataA2AServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = ( + _BaseDataA2AServiceRestTransport._BaseListOperations._get_http_options() + ) + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataA2AServiceRestTransport._BaseListOperations, + "_BaseListOperations__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1alpha.DataA2AServiceClient.ListOperations", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataA2AServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1alpha.DataA2AServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("DataA2AServiceRestTransport",) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/rest_base.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/rest_base.py new file mode 100644 index 000000000000..1aeca5917b15 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_a2a_service/transports/rest_base.py @@ -0,0 +1,240 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.geminidataanalytics_v1alpha.types import data_a2a_service + +from .base import DEFAULT_CLIENT_INFO, DataA2AServiceTransport + + +class _BaseDataA2AServiceRestTransport(DataA2AServiceTransport): + """Base REST backend transport for DataA2AService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "geminidataanalytics.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'geminidataanalytics.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseGetAgentCard: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/a2a/{tenant=projects/*/locations/*/agents/*}/v1/card", + }, + { + "method": "get", + "uri": "/v1alpha/a2a/{tenant=projects/*/locations/*/dataAgents/*}/v1/card", + }, + ] + return http_options + + class _BaseSendMessage: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/a2a/{tenant=projects/*/locations/*/agents/*}/v1/message:send", + "body": "*", + }, + { + "method": "post", + "uri": "/v1alpha/a2a/{tenant=projects/*/locations/*/dataAgents/*}/v1/message:send", + "body": "*", + }, + ] + return http_options + + class _BaseSendStreamingMessage: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/a2a/{tenant=projects/*/locations/*/agents/*}/v1/message:stream", + "body": "*", + }, + { + "method": "post", + "uri": "/v1alpha/a2a/{tenant=projects/*/locations/*/dataAgents/*}/v1/message:stream", + "body": "*", + }, + ] + return http_options + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*}", + }, + ] + return http_options + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*}/locations", + }, + ] + return http_options + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + +__all__ = ("_BaseDataA2AServiceRestTransport",) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/async_client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/async_client.py index 6fa10abffe99..fdb39908dd01 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/async_client.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/async_client.py @@ -59,6 +59,7 @@ data_agent, data_agent_service, data_analytics_agent, + datasource, ) from google.cloud.geminidataanalytics_v1alpha.types import data_agent as gcg_data_agent @@ -88,6 +89,8 @@ class DataAgentServiceAsyncClient: _DEFAULT_ENDPOINT_TEMPLATE = DataAgentServiceClient._DEFAULT_ENDPOINT_TEMPLATE _DEFAULT_UNIVERSE = DataAgentServiceClient._DEFAULT_UNIVERSE + crypto_key_path = staticmethod(DataAgentServiceClient.crypto_key_path) + parse_crypto_key_path = staticmethod(DataAgentServiceClient.parse_crypto_key_path) data_agent_path = staticmethod(DataAgentServiceClient.data_agent_path) parse_data_agent_path = staticmethod(DataAgentServiceClient.parse_data_agent_path) common_billing_account_path = staticmethod( @@ -1728,6 +1731,290 @@ async def sample_set_iam_policy(): # Done; return the response. return response + async def set_agent_ops_observability( + self, + request: Optional[ + Union[data_agent_service.SetAgentOpsObservabilityRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + telemetry_enabled: Optional[bool] = None, + data_source_type: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Enables/Disables required GCP services and configures + AgentOps observability settings calling the Admin + Settings executable node to update the AgentOps + Observability feature. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1alpha + + async def sample_set_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1alpha.DataAgentServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.SetAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + operation = await client.set_agent_ops_observability(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.geminidataanalytics_v1alpha.types.SetAgentOpsObservabilityRequest, dict]]): + The request object. Request for SetAgentOpsObservability. + parent (:class:`str`): + Required. Parent value for + SetAgentOpsObservabilityRequest. Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + telemetry_enabled (:class:`bool`): + Optional. Whether to enable or disable AgentOps + observability. When update_mask is provided, this field + is ignored unless specified in the mask. + + This corresponds to the ``telemetry_enabled`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_source_type (:class:`str`): + Required. The data source type for + which to set observability settings. + Examples: "bigquery", "looker" + + This corresponds to the ``data_source_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.geminidataanalytics_v1alpha.types.SetAgentOpsObservabilityResponse` + Response for SetAgentOpsObservability. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, telemetry_enabled, data_source_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, data_agent_service.SetAgentOpsObservabilityRequest): + request = data_agent_service.SetAgentOpsObservabilityRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if telemetry_enabled is not None: + request.telemetry_enabled = telemetry_enabled + if data_source_type is not None: + request.data_source_type = data_source_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.set_agent_ops_observability + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + data_agent_service.SetAgentOpsObservabilityResponse, + metadata_type=data_agent_service.SetAgentOpsObservabilityMetadata, + ) + + # Done; return the response. + return response + + async def retrieve_agent_ops_observability( + self, + request: Optional[ + Union[data_agent_service.RetrieveAgentOpsObservabilityRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + data_source_type: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_agent_service.RetrieveAgentOpsObservabilityResponse: + r"""Gets AgentOps observability settings and status of + required services. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1alpha + + async def sample_retrieve_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1alpha.DataAgentServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.RetrieveAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + response = await client.retrieve_agent_ops_observability(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.geminidataanalytics_v1alpha.types.RetrieveAgentOpsObservabilityRequest, dict]]): + The request object. Request for + RetrieveAgentOpsObservability. + parent (:class:`str`): + Required. Parent value for + RetrieveAgentOpsObservabilityRequest. + Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_source_type (:class:`str`): + Required. The data source type for + which to retrieve observability + settings. Examples: "bigquery", "looker" + + This corresponds to the ``data_source_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1alpha.types.RetrieveAgentOpsObservabilityResponse: + Response for + RetrieveAgentOpsObservability. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, data_source_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, data_agent_service.RetrieveAgentOpsObservabilityRequest + ): + request = data_agent_service.RetrieveAgentOpsObservabilityRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if data_source_type is not None: + request.data_source_type = data_source_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.retrieve_agent_ops_observability + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def list_operations( self, request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/client.py index 99dde90822b6..dd6924852fde 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/client.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/client.py @@ -83,6 +83,7 @@ data_agent, data_agent_service, data_analytics_agent, + datasource, ) from google.cloud.geminidataanalytics_v1alpha.types import data_agent as gcg_data_agent @@ -184,6 +185,30 @@ def transport(self) -> DataAgentServiceTransport: """ return self._transport + @staticmethod + def crypto_key_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + ) -> str: + """Returns a fully-qualified crypto_key string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + ) + + @staticmethod + def parse_crypto_key_path(path: str) -> Dict[str, str]: + """Parses a crypto_key path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def data_agent_path( project: str, @@ -2003,6 +2028,288 @@ def sample_set_iam_policy(): # Done; return the response. return response + def set_agent_ops_observability( + self, + request: Optional[ + Union[data_agent_service.SetAgentOpsObservabilityRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + telemetry_enabled: Optional[bool] = None, + data_source_type: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Enables/Disables required GCP services and configures + AgentOps observability settings calling the Admin + Settings executable node to update the AgentOps + Observability feature. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1alpha + + def sample_set_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1alpha.DataAgentServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.SetAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + operation = client.set_agent_ops_observability(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.geminidataanalytics_v1alpha.types.SetAgentOpsObservabilityRequest, dict]): + The request object. Request for SetAgentOpsObservability. + parent (str): + Required. Parent value for + SetAgentOpsObservabilityRequest. Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + telemetry_enabled (bool): + Optional. Whether to enable or disable AgentOps + observability. When update_mask is provided, this field + is ignored unless specified in the mask. + + This corresponds to the ``telemetry_enabled`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_source_type (str): + Required. The data source type for + which to set observability settings. + Examples: "bigquery", "looker" + + This corresponds to the ``data_source_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.geminidataanalytics_v1alpha.types.SetAgentOpsObservabilityResponse` + Response for SetAgentOpsObservability. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, telemetry_enabled, data_source_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, data_agent_service.SetAgentOpsObservabilityRequest): + request = data_agent_service.SetAgentOpsObservabilityRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if telemetry_enabled is not None: + request.telemetry_enabled = telemetry_enabled + if data_source_type is not None: + request.data_source_type = data_source_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.set_agent_ops_observability + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + data_agent_service.SetAgentOpsObservabilityResponse, + metadata_type=data_agent_service.SetAgentOpsObservabilityMetadata, + ) + + # Done; return the response. + return response + + def retrieve_agent_ops_observability( + self, + request: Optional[ + Union[data_agent_service.RetrieveAgentOpsObservabilityRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + data_source_type: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_agent_service.RetrieveAgentOpsObservabilityResponse: + r"""Gets AgentOps observability settings and status of + required services. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1alpha + + def sample_retrieve_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1alpha.DataAgentServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.RetrieveAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + response = client.retrieve_agent_ops_observability(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.geminidataanalytics_v1alpha.types.RetrieveAgentOpsObservabilityRequest, dict]): + The request object. Request for + RetrieveAgentOpsObservability. + parent (str): + Required. Parent value for + RetrieveAgentOpsObservabilityRequest. + Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_source_type (str): + Required. The data source type for + which to retrieve observability + settings. Examples: "bigquery", "looker" + + This corresponds to the ``data_source_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1alpha.types.RetrieveAgentOpsObservabilityResponse: + Response for + RetrieveAgentOpsObservability. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, data_source_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, data_agent_service.RetrieveAgentOpsObservabilityRequest + ): + request = data_agent_service.RetrieveAgentOpsObservabilityRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if data_source_type is not None: + request.data_source_type = data_source_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.retrieve_agent_ops_observability + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "DataAgentServiceClient": return self diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/base.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/base.py index b807945e1ce1..625a9afd3940 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/base.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/base.py @@ -204,6 +204,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.set_agent_ops_observability: gapic_v1.method.wrap_method( + self.set_agent_ops_observability, + default_timeout=None, + client_info=client_info, + ), + self.retrieve_agent_ops_observability: gapic_v1.method.wrap_method( + self.retrieve_agent_ops_observability, + default_timeout=None, + client_info=client_info, + ), self.get_location: gapic_v1.method.wrap_method( self.get_location, default_timeout=None, @@ -355,6 +365,27 @@ def set_iam_policy( ]: raise NotImplementedError() + @property + def set_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.SetAgentOpsObservabilityRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def retrieve_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.RetrieveAgentOpsObservabilityRequest], + Union[ + data_agent_service.RetrieveAgentOpsObservabilityResponse, + Awaitable[data_agent_service.RetrieveAgentOpsObservabilityResponse], + ], + ]: + raise NotImplementedError() + @property def list_operations( self, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/grpc.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/grpc.py index 2ec7f43bf02e..6a8a2ee7101c 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/grpc.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/grpc.py @@ -659,6 +659,72 @@ def set_iam_policy( ) return self._stubs["set_iam_policy"] + @property + def set_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.SetAgentOpsObservabilityRequest], operations_pb2.Operation + ]: + r"""Return a callable for the set agent ops observability method over gRPC. + + Enables/Disables required GCP services and configures + AgentOps observability settings calling the Admin + Settings executable node to update the AgentOps + Observability feature. + + Returns: + Callable[[~.SetAgentOpsObservabilityRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent_ops_observability" not in self._stubs: + self._stubs["set_agent_ops_observability"] = ( + self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1alpha.DataAgentService/SetAgentOpsObservability", + request_serializer=data_agent_service.SetAgentOpsObservabilityRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["set_agent_ops_observability"] + + @property + def retrieve_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.RetrieveAgentOpsObservabilityRequest], + data_agent_service.RetrieveAgentOpsObservabilityResponse, + ]: + r"""Return a callable for the retrieve agent ops + observability method over gRPC. + + Gets AgentOps observability settings and status of + required services. + + Returns: + Callable[[~.RetrieveAgentOpsObservabilityRequest], + ~.RetrieveAgentOpsObservabilityResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "retrieve_agent_ops_observability" not in self._stubs: + self._stubs["retrieve_agent_ops_observability"] = ( + self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1alpha.DataAgentService/RetrieveAgentOpsObservability", + request_serializer=data_agent_service.RetrieveAgentOpsObservabilityRequest.serialize, + response_deserializer=data_agent_service.RetrieveAgentOpsObservabilityResponse.deserialize, + ) + ) + return self._stubs["retrieve_agent_ops_observability"] + def close(self): self._logged_channel.close() diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/grpc_asyncio.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/grpc_asyncio.py index 6491425186a8..5c202b800c26 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/grpc_asyncio.py @@ -671,6 +671,73 @@ def set_iam_policy( ) return self._stubs["set_iam_policy"] + @property + def set_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.SetAgentOpsObservabilityRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the set agent ops observability method over gRPC. + + Enables/Disables required GCP services and configures + AgentOps observability settings calling the Admin + Settings executable node to update the AgentOps + Observability feature. + + Returns: + Callable[[~.SetAgentOpsObservabilityRequest], + 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 "set_agent_ops_observability" not in self._stubs: + self._stubs["set_agent_ops_observability"] = ( + self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1alpha.DataAgentService/SetAgentOpsObservability", + request_serializer=data_agent_service.SetAgentOpsObservabilityRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["set_agent_ops_observability"] + + @property + def retrieve_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.RetrieveAgentOpsObservabilityRequest], + Awaitable[data_agent_service.RetrieveAgentOpsObservabilityResponse], + ]: + r"""Return a callable for the retrieve agent ops + observability method over gRPC. + + Gets AgentOps observability settings and status of + required services. + + Returns: + Callable[[~.RetrieveAgentOpsObservabilityRequest], + Awaitable[~.RetrieveAgentOpsObservabilityResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "retrieve_agent_ops_observability" not in self._stubs: + self._stubs["retrieve_agent_ops_observability"] = ( + self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1alpha.DataAgentService/RetrieveAgentOpsObservability", + request_serializer=data_agent_service.RetrieveAgentOpsObservabilityRequest.serialize, + response_deserializer=data_agent_service.RetrieveAgentOpsObservabilityResponse.deserialize, + ) + ) + return self._stubs["retrieve_agent_ops_observability"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -729,6 +796,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.set_agent_ops_observability: self._wrap_method( + self.set_agent_ops_observability, + default_timeout=None, + client_info=client_info, + ), + self.retrieve_agent_ops_observability: self._wrap_method( + self.retrieve_agent_ops_observability, + default_timeout=None, + client_info=client_info, + ), self.get_location: self._wrap_method( self.get_location, default_timeout=None, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/rest.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/rest.py index 38c848d85458..72176e9fbd58 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/rest.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/rest.py @@ -141,6 +141,22 @@ def post_list_data_agents(self, response): logging.log(f"Received response: {response}") return response + def pre_retrieve_agent_ops_observability(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_retrieve_agent_ops_observability(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_agent_ops_observability(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_agent_ops_observability(self, response): + logging.log(f"Received response: {response}") + return response + def pre_set_iam_policy(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -531,6 +547,107 @@ def post_list_data_agents_with_metadata( """ return response, metadata + def pre_retrieve_agent_ops_observability( + self, + request: data_agent_service.RetrieveAgentOpsObservabilityRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_agent_service.RetrieveAgentOpsObservabilityRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for retrieve_agent_ops_observability + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataAgentService server. + """ + return request, metadata + + def post_retrieve_agent_ops_observability( + self, response: data_agent_service.RetrieveAgentOpsObservabilityResponse + ) -> data_agent_service.RetrieveAgentOpsObservabilityResponse: + """Post-rpc interceptor for retrieve_agent_ops_observability + + DEPRECATED. Please use the `post_retrieve_agent_ops_observability_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DataAgentService server but before + it is returned to user code. This `post_retrieve_agent_ops_observability` interceptor runs + before the `post_retrieve_agent_ops_observability_with_metadata` interceptor. + """ + return response + + def post_retrieve_agent_ops_observability_with_metadata( + self, + response: data_agent_service.RetrieveAgentOpsObservabilityResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_agent_service.RetrieveAgentOpsObservabilityResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for retrieve_agent_ops_observability + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DataAgentService server but before it is returned to user code. + + We recommend only using this `post_retrieve_agent_ops_observability_with_metadata` + interceptor in new development instead of the `post_retrieve_agent_ops_observability` interceptor. + When both interceptors are used, this `post_retrieve_agent_ops_observability_with_metadata` interceptor runs after the + `post_retrieve_agent_ops_observability` interceptor. The (possibly modified) response returned by + `post_retrieve_agent_ops_observability` will be passed to + `post_retrieve_agent_ops_observability_with_metadata`. + """ + return response, metadata + + def pre_set_agent_ops_observability( + self, + request: data_agent_service.SetAgentOpsObservabilityRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_agent_service.SetAgentOpsObservabilityRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for set_agent_ops_observability + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataAgentService server. + """ + return request, metadata + + def post_set_agent_ops_observability( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for set_agent_ops_observability + + DEPRECATED. Please use the `post_set_agent_ops_observability_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DataAgentService server but before + it is returned to user code. This `post_set_agent_ops_observability` interceptor runs + before the `post_set_agent_ops_observability_with_metadata` interceptor. + """ + return response + + def post_set_agent_ops_observability_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for set_agent_ops_observability + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DataAgentService server but before it is returned to user code. + + We recommend only using this `post_set_agent_ops_observability_with_metadata` + interceptor in new development instead of the `post_set_agent_ops_observability` interceptor. + When both interceptors are used, this `post_set_agent_ops_observability_with_metadata` interceptor runs after the + `post_set_agent_ops_observability` interceptor. The (possibly modified) response returned by + `post_set_agent_ops_observability` will be passed to + `post_set_agent_ops_observability_with_metadata`. + """ + return response, metadata + def pre_set_iam_policy( self, request: iam_policy_pb2.SetIamPolicyRequest, @@ -2198,6 +2315,312 @@ def __call__( ) return resp + class _RetrieveAgentOpsObservability( + _BaseDataAgentServiceRestTransport._BaseRetrieveAgentOpsObservability, + DataAgentServiceRestStub, + ): + def __hash__(self): + return hash("DataAgentServiceRestTransport.RetrieveAgentOpsObservability") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: data_agent_service.RetrieveAgentOpsObservabilityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_agent_service.RetrieveAgentOpsObservabilityResponse: + r"""Call the retrieve agent ops + observability method over HTTP. + + Args: + request (~.data_agent_service.RetrieveAgentOpsObservabilityRequest): + The request object. Request for + RetrieveAgentOpsObservability. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.data_agent_service.RetrieveAgentOpsObservabilityResponse: + Response for + RetrieveAgentOpsObservability. + + """ + + http_options = _BaseDataAgentServiceRestTransport._BaseRetrieveAgentOpsObservability._get_http_options() + request, metadata = self._interceptor.pre_retrieve_agent_ops_observability( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataAgentServiceRestTransport._BaseRetrieveAgentOpsObservability, + "_BaseRetrieveAgentOpsObservability__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.RetrieveAgentOpsObservability", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", + "rpcName": "RetrieveAgentOpsObservability", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataAgentServiceRestTransport._RetrieveAgentOpsObservability._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = data_agent_service.RetrieveAgentOpsObservabilityResponse() + pb_resp = data_agent_service.RetrieveAgentOpsObservabilityResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_retrieve_agent_ops_observability(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_retrieve_agent_ops_observability_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = data_agent_service.RetrieveAgentOpsObservabilityResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.retrieve_agent_ops_observability", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", + "rpcName": "RetrieveAgentOpsObservability", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SetAgentOpsObservability( + _BaseDataAgentServiceRestTransport._BaseSetAgentOpsObservability, + DataAgentServiceRestStub, + ): + def __hash__(self): + return hash("DataAgentServiceRestTransport.SetAgentOpsObservability") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: data_agent_service.SetAgentOpsObservabilityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the set agent ops + observability method over HTTP. + + Args: + request (~.data_agent_service.SetAgentOpsObservabilityRequest): + The request object. Request for SetAgentOpsObservability. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseDataAgentServiceRestTransport._BaseSetAgentOpsObservability._get_http_options() + request, metadata = self._interceptor.pre_set_agent_ops_observability( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataAgentServiceRestTransport._BaseSetAgentOpsObservability, + "_BaseSetAgentOpsObservability__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.SetAgentOpsObservability", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", + "rpcName": "SetAgentOpsObservability", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + DataAgentServiceRestTransport._SetAgentOpsObservability._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_set_agent_ops_observability(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_set_agent_ops_observability_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.set_agent_ops_observability", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", + "rpcName": "SetAgentOpsObservability", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _SetIamPolicy( _BaseDataAgentServiceRestTransport._BaseSetIamPolicy, DataAgentServiceRestStub ): @@ -2797,6 +3220,31 @@ def list_data_agents( # In C++ this would require a dynamic_cast return self._ListDataAgents(self._session, self._host, self._interceptor) # type: ignore + @property + def retrieve_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.RetrieveAgentOpsObservabilityRequest], + data_agent_service.RetrieveAgentOpsObservabilityResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RetrieveAgentOpsObservability( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def set_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.SetAgentOpsObservabilityRequest], 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._SetAgentOpsObservability( + self._session, self._host, self._interceptor + ) # type: ignore + @property def set_iam_policy( self, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/rest_base.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/rest_base.py index 61c90262993d..3278040f5584 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/rest_base.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_agent_service/transports/rest_base.py @@ -227,6 +227,41 @@ def _get_http_options(): ] return http_options + class _BaseRetrieveAgentOpsObservability: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "dataSourceType": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=projects/*/locations/*}:retrieveAgentOpsObservability", + }, + ] + return http_options + + class _BaseSetAgentOpsObservability: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=projects/*/locations/*}/observabilitySettings:setAgentOpsObservability", + "body": "*", + }, + ] + return http_options + class _BaseSetIamPolicy: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/async_client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/async_client.py index b889e4c99d93..2ebe87ee56c6 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/async_client.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/async_client.py @@ -46,6 +46,7 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.struct_pb2 as struct_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore @@ -55,6 +56,7 @@ from google.cloud.geminidataanalytics_v1alpha.types import ( conversation, data_chat_service, + usage, ) from google.cloud.geminidataanalytics_v1alpha.types import ( conversation as gcg_conversation, @@ -93,6 +95,8 @@ class DataChatServiceAsyncClient: parse_conversation_path = staticmethod( DataChatServiceClient.parse_conversation_path ) + crypto_key_path = staticmethod(DataChatServiceClient.crypto_key_path) + parse_crypto_key_path = staticmethod(DataChatServiceClient.parse_crypto_key_path) data_agent_path = staticmethod(DataChatServiceClient.data_agent_path) parse_data_agent_path = staticmethod(DataChatServiceClient.parse_data_agent_path) common_billing_account_path = staticmethod( @@ -324,8 +328,7 @@ def chat( metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> Awaitable[AsyncIterable[data_chat_service.Message]]: r"""Answers a data question by generating a stream of - [Message][google.cloud.geminidataanalytics.v1alpha.Message] - objects. + [Message][google.cloud.geminidataanalytics.v1.Message] objects. .. code-block:: python @@ -641,6 +644,136 @@ async def sample_delete_conversation(): metadata=metadata, ) + async def update_conversation( + self, + request: Optional[ + Union[gcg_conversation.UpdateConversationRequest, dict] + ] = None, + *, + conversation: Optional[gcg_conversation.Conversation] = 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, Union[str, bytes]]] = (), + ) -> gcg_conversation.Conversation: + r"""Updates a conversation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1alpha + + async def sample_update_conversation(): + # Create a client + client = geminidataanalytics_v1alpha.DataChatServiceAsyncClient() + + # Initialize request argument(s) + conversation = geminidataanalytics_v1alpha.Conversation() + conversation.agents = ['agents_value1', 'agents_value2'] + + request = geminidataanalytics_v1alpha.UpdateConversationRequest( + conversation=conversation, + ) + + # Make the request + response = await client.update_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.geminidataanalytics_v1alpha.types.UpdateConversationRequest, dict]]): + The request object. Request for updating a conversation. + conversation (:class:`google.cloud.geminidataanalytics_v1alpha.types.Conversation`): + Required. The resource being updated. + This corresponds to the ``conversation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the Conversation resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields with non-default values + present in the request will be overwritten. If a + wildcard mask is provided, all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1alpha.types.Conversation: + Message for a conversation. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [conversation, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcg_conversation.UpdateConversationRequest): + request = gcg_conversation.UpdateConversationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if conversation is not None: + request.conversation = conversation + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_conversation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("conversation.name", request.conversation.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def get_conversation( self, request: Optional[Union[conversation.GetConversationRequest, dict]] = None, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/client.py index d36ace128af7..e17e9c1a729c 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/client.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/client.py @@ -69,6 +69,7 @@ _LOGGER = std_logging.getLogger(__name__) +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.struct_pb2 as struct_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore @@ -78,6 +79,7 @@ from google.cloud.geminidataanalytics_v1alpha.types import ( conversation, data_chat_service, + usage, ) from google.cloud.geminidataanalytics_v1alpha.types import ( conversation as gcg_conversation, @@ -206,6 +208,30 @@ def parse_conversation_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def crypto_key_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + ) -> str: + """Returns a fully-qualified crypto_key string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + ) + + @staticmethod + def parse_crypto_key_path(path: str) -> Dict[str, str]: + """Parses a crypto_key path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def data_agent_path( project: str, @@ -638,8 +664,7 @@ def chat( metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> Iterable[data_chat_service.Message]: r"""Answers a data question by generating a stream of - [Message][google.cloud.geminidataanalytics.v1alpha.Message] - objects. + [Message][google.cloud.geminidataanalytics.v1.Message] objects. .. code-block:: python @@ -949,6 +974,133 @@ def sample_delete_conversation(): metadata=metadata, ) + def update_conversation( + self, + request: Optional[ + Union[gcg_conversation.UpdateConversationRequest, dict] + ] = None, + *, + conversation: Optional[gcg_conversation.Conversation] = 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, Union[str, bytes]]] = (), + ) -> gcg_conversation.Conversation: + r"""Updates a conversation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1alpha + + def sample_update_conversation(): + # Create a client + client = geminidataanalytics_v1alpha.DataChatServiceClient() + + # Initialize request argument(s) + conversation = geminidataanalytics_v1alpha.Conversation() + conversation.agents = ['agents_value1', 'agents_value2'] + + request = geminidataanalytics_v1alpha.UpdateConversationRequest( + conversation=conversation, + ) + + # Make the request + response = client.update_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.geminidataanalytics_v1alpha.types.UpdateConversationRequest, dict]): + The request object. Request for updating a conversation. + conversation (google.cloud.geminidataanalytics_v1alpha.types.Conversation): + Required. The resource being updated. + This corresponds to the ``conversation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Conversation resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields with non-default values + present in the request will be overwritten. If a + wildcard mask is provided, all fields will be + overwritten. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1alpha.types.Conversation: + Message for a conversation. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [conversation, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcg_conversation.UpdateConversationRequest): + request = gcg_conversation.UpdateConversationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if conversation is not None: + request.conversation = conversation + 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_conversation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("conversation.name", request.conversation.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def get_conversation( self, request: Optional[Union[conversation.GetConversationRequest, dict]] = None, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/base.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/base.py index 64de989ee45f..ac944e076f34 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/base.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/base.py @@ -164,6 +164,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.update_conversation: gapic_v1.method.wrap_method( + self.update_conversation, + default_timeout=None, + client_info=client_info, + ), self.get_conversation: gapic_v1.method.wrap_method( self.get_conversation, default_timeout=None, @@ -252,6 +257,15 @@ def delete_conversation( ]: raise NotImplementedError() + @property + def update_conversation( + self, + ) -> Callable[ + [gcg_conversation.UpdateConversationRequest], + Union[gcg_conversation.Conversation, Awaitable[gcg_conversation.Conversation]], + ]: + raise NotImplementedError() + @property def get_conversation( self, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/grpc.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/grpc.py index eea0872f149e..7b1c3b6a5a2b 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/grpc.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/grpc.py @@ -343,8 +343,7 @@ def chat( r"""Return a callable for the chat method over gRPC. Answers a data question by generating a stream of - [Message][google.cloud.geminidataanalytics.v1alpha.Message] - objects. + [Message][google.cloud.geminidataanalytics.v1.Message] objects. Returns: Callable[[~.ChatRequest], @@ -420,6 +419,34 @@ def delete_conversation( ) return self._stubs["delete_conversation"] + @property + def update_conversation( + self, + ) -> Callable[ + [gcg_conversation.UpdateConversationRequest], gcg_conversation.Conversation + ]: + r"""Return a callable for the update conversation method over gRPC. + + Updates a conversation. + + Returns: + Callable[[~.UpdateConversationRequest], + ~.Conversation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation" not in self._stubs: + self._stubs["update_conversation"] = self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1alpha.DataChatService/UpdateConversation", + request_serializer=gcg_conversation.UpdateConversationRequest.serialize, + response_deserializer=gcg_conversation.Conversation.deserialize, + ) + return self._stubs["update_conversation"] + @property def get_conversation( self, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/grpc_asyncio.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/grpc_asyncio.py index abe521295cb6..62b68aff0f13 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/grpc_asyncio.py @@ -353,8 +353,7 @@ def chat( r"""Return a callable for the chat method over gRPC. Answers a data question by generating a stream of - [Message][google.cloud.geminidataanalytics.v1alpha.Message] - objects. + [Message][google.cloud.geminidataanalytics.v1.Message] objects. Returns: Callable[[~.ChatRequest], @@ -431,6 +430,35 @@ def delete_conversation( ) return self._stubs["delete_conversation"] + @property + def update_conversation( + self, + ) -> Callable[ + [gcg_conversation.UpdateConversationRequest], + Awaitable[gcg_conversation.Conversation], + ]: + r"""Return a callable for the update conversation method over gRPC. + + Updates a conversation. + + Returns: + Callable[[~.UpdateConversationRequest], + Awaitable[~.Conversation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation" not in self._stubs: + self._stubs["update_conversation"] = self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1alpha.DataChatService/UpdateConversation", + request_serializer=gcg_conversation.UpdateConversationRequest.serialize, + response_deserializer=gcg_conversation.Conversation.deserialize, + ) + return self._stubs["update_conversation"] + @property def get_conversation( self, @@ -565,6 +593,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.update_conversation: self._wrap_method( + self.update_conversation, + default_timeout=None, + client_info=client_info, + ), self.get_conversation: self._wrap_method( self.get_conversation, default_timeout=None, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/rest.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/rest.py index 20ff9fcf598f..9e7344757c6e 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/rest.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/rest.py @@ -133,6 +133,14 @@ def post_query_data(self, response): logging.log(f"Received response: {response}") return response + def pre_update_conversation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_conversation(self, response): + logging.log(f"Received response: {response}") + return response + transport = DataChatServiceRestTransport(interceptor=MyCustomDataChatServiceInterceptor()) client = DataChatServiceClient(transport=transport) @@ -448,6 +456,55 @@ def post_query_data_with_metadata( """ return response, metadata + def pre_update_conversation( + self, + request: gcg_conversation.UpdateConversationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcg_conversation.UpdateConversationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataChatService server. + """ + return request, metadata + + def post_update_conversation( + self, response: gcg_conversation.Conversation + ) -> gcg_conversation.Conversation: + """Post-rpc interceptor for update_conversation + + DEPRECATED. Please use the `post_update_conversation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DataChatService server but before + it is returned to user code. This `post_update_conversation` interceptor runs + before the `post_update_conversation_with_metadata` interceptor. + """ + return response + + def post_update_conversation_with_metadata( + self, + response: gcg_conversation.Conversation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcg_conversation.Conversation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_conversation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DataChatService server but before it is returned to user code. + + We recommend only using this `post_update_conversation_with_metadata` + interceptor in new development instead of the `post_update_conversation` interceptor. + When both interceptors are used, this `post_update_conversation_with_metadata` interceptor runs after the + `post_update_conversation` interceptor. The (possibly modified) response returned by + `post_update_conversation` will be passed to + `post_update_conversation_with_metadata`. + """ + return response, metadata + def pre_get_location( self, request: locations_pb2.GetLocationRequest, @@ -1682,6 +1739,154 @@ def __call__( ) return resp + class _UpdateConversation( + _BaseDataChatServiceRestTransport._BaseUpdateConversation, + DataChatServiceRestStub, + ): + def __hash__(self): + return hash("DataChatServiceRestTransport.UpdateConversation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gcg_conversation.UpdateConversationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcg_conversation.Conversation: + r"""Call the update conversation method over HTTP. + + Args: + request (~.gcg_conversation.UpdateConversationRequest): + The request object. Request for updating a conversation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcg_conversation.Conversation: + Message for a conversation. + """ + + http_options = _BaseDataChatServiceRestTransport._BaseUpdateConversation._get_http_options() + request, metadata = self._interceptor.pre_update_conversation( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataChatServiceRestTransport._BaseUpdateConversation, + "_BaseUpdateConversation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1alpha.DataChatServiceClient.UpdateConversation", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataChatService", + "rpcName": "UpdateConversation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataChatServiceRestTransport._UpdateConversation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcg_conversation.Conversation() + pb_resp = gcg_conversation.Conversation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_conversation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_conversation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcg_conversation.Conversation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1alpha.DataChatServiceClient.update_conversation", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1alpha.DataChatService", + "rpcName": "UpdateConversation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + @property def chat( self, @@ -1746,6 +1951,16 @@ def query_data( # In C++ this would require a dynamic_cast return self._QueryData(self._session, self._host, self._interceptor) # type: ignore + @property + def update_conversation( + self, + ) -> Callable[ + [gcg_conversation.UpdateConversationRequest], gcg_conversation.Conversation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateConversation(self._session, self._host, self._interceptor) # type: ignore + @property def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/rest_base.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/rest_base.py index 76dffe6cfa1a..b5c01ce9dbb7 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/rest_base.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/transports/rest_base.py @@ -211,6 +211,23 @@ def _get_http_options(): ] return http_options + class _BaseUpdateConversation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1alpha/{conversation.name=projects/*/locations/*/conversations/*}", + "body": "conversation", + }, + ] + return http_options + class _BaseGetLocation: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/__init__.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/__init__.py index 7774564b2797..328d69174eb5 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/__init__.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/__init__.py @@ -18,14 +18,24 @@ ) from .context import ( AnalysisOptions, + BigQueryRoutine, + BigQueryRoutineReference, ChartOptions, + Citation, + CitationAnchor, + CitationSource, Context, ConversationOptions, DatasourceOptions, + DynamicField, ExampleQuery, GlossaryTerm, LookerGoldenQuery, LookerQuery, + MatchedQuery, + QueryParameter, + QueryParameterValues, + UserFunctions, ) from .conversation import ( Conversation, @@ -34,11 +44,52 @@ GetConversationRequest, ListConversationsRequest, ListConversationsResponse, + UpdateConversationRequest, ) from .credentials import ( Credentials, OAuthCredentials, ) +from .data_a2a_service import ( + A2AArtifact, + A2AMessage, + A2ATask, + AgentCapabilities, + AgentCard, + AgentCardSignature, + AgentExtension, + AgentInterface, + AgentProvider, + AgentSkill, + APIKeySecurityScheme, + AuthenticationInfo, + AuthorizationCodeOAuthFlow, + ClientCredentialsOAuthFlow, + DataPart, + FilePart, + GetAgentCardRequest, + HTTPAuthSecurityScheme, + ImplicitOAuthFlow, + MutualTlsSecurityScheme, + OAuth2SecurityScheme, + OAuthFlows, + OpenIdConnectSecurityScheme, + Part, + PasswordOAuthFlow, + PushNotificationConfig, + Role, + Security, + SecurityScheme, + SendMessageConfiguration, + SendMessageRequest, + SendMessageResponse, + StreamResponse, + StringList, + TaskArtifactUpdateEvent, + TaskState, + TaskStatus, + TaskStatusUpdateEvent, +) from .data_agent import ( DataAgent, ) @@ -51,6 +102,11 @@ ListDataAgentsRequest, ListDataAgentsResponse, OperationMetadata, + RetrieveAgentOpsObservabilityRequest, + RetrieveAgentOpsObservabilityResponse, + SetAgentOpsObservabilityMetadata, + SetAgentOpsObservabilityRequest, + SetAgentOpsObservabilityResponse, UpdateDataAgentRequest, ) from .data_analytics_agent import ( @@ -80,6 +136,7 @@ GenerationOptions, ListMessagesRequest, ListMessagesResponse, + LookerSettings, Message, ParameterizedSecureViewParameters, QueryDataContext, @@ -96,6 +153,7 @@ from .datasource import ( AlloyDbDatabaseReference, AlloyDbReference, + BigQueryPropertyGraphReference, BigQueryTableReference, BigQueryTableReferences, BigtableDatabaseReference, @@ -119,26 +177,78 @@ StudioDatasourceReference, StudioDatasourceReferences, ) +from .usage import ( + TokenUsage, +) __all__ = ( "AgentContextReference", "AnalysisOptions", + "BigQueryRoutine", + "BigQueryRoutineReference", "ChartOptions", + "Citation", + "CitationAnchor", + "CitationSource", "Context", "ConversationOptions", "DatasourceOptions", + "DynamicField", "ExampleQuery", "GlossaryTerm", "LookerGoldenQuery", "LookerQuery", + "MatchedQuery", + "QueryParameter", + "QueryParameterValues", + "UserFunctions", "Conversation", "CreateConversationRequest", "DeleteConversationRequest", "GetConversationRequest", "ListConversationsRequest", "ListConversationsResponse", + "UpdateConversationRequest", "Credentials", "OAuthCredentials", + "A2AArtifact", + "A2AMessage", + "A2ATask", + "AgentCapabilities", + "AgentCard", + "AgentCardSignature", + "AgentExtension", + "AgentInterface", + "AgentProvider", + "AgentSkill", + "APIKeySecurityScheme", + "AuthenticationInfo", + "AuthorizationCodeOAuthFlow", + "ClientCredentialsOAuthFlow", + "DataPart", + "FilePart", + "GetAgentCardRequest", + "HTTPAuthSecurityScheme", + "ImplicitOAuthFlow", + "MutualTlsSecurityScheme", + "OAuth2SecurityScheme", + "OAuthFlows", + "OpenIdConnectSecurityScheme", + "Part", + "PasswordOAuthFlow", + "PushNotificationConfig", + "Security", + "SecurityScheme", + "SendMessageConfiguration", + "SendMessageRequest", + "SendMessageResponse", + "StreamResponse", + "StringList", + "TaskArtifactUpdateEvent", + "TaskStatus", + "TaskStatusUpdateEvent", + "Role", + "TaskState", "DataAgent", "CreateDataAgentRequest", "DeleteDataAgentRequest", @@ -148,6 +258,11 @@ "ListDataAgentsRequest", "ListDataAgentsResponse", "OperationMetadata", + "RetrieveAgentOpsObservabilityRequest", + "RetrieveAgentOpsObservabilityResponse", + "SetAgentOpsObservabilityMetadata", + "SetAgentOpsObservabilityRequest", + "SetAgentOpsObservabilityResponse", "UpdateDataAgentRequest", "DataAnalyticsAgent", "AnalysisEvent", @@ -173,6 +288,7 @@ "GenerationOptions", "ListMessagesRequest", "ListMessagesResponse", + "LookerSettings", "Message", "ParameterizedSecureViewParameters", "QueryDataContext", @@ -187,6 +303,7 @@ "UserMessage", "AlloyDbDatabaseReference", "AlloyDbReference", + "BigQueryPropertyGraphReference", "BigQueryTableReference", "BigQueryTableReferences", "BigtableDatabaseReference", @@ -209,4 +326,5 @@ "StudioDatasourceReference", "StudioDatasourceReferences", "DataFilterType", + "TokenUsage", ) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/context.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/context.py index 292fa39f7142..1a02680984e1 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/context.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/context.py @@ -26,14 +26,24 @@ package="google.cloud.geminidataanalytics.v1alpha", manifest={ "Context", + "UserFunctions", + "BigQueryRoutine", + "BigQueryRoutineReference", "ExampleQuery", + "QueryParameter", + "MatchedQuery", + "QueryParameterValues", "LookerGoldenQuery", + "DynamicField", "LookerQuery", "GlossaryTerm", "ConversationOptions", "DatasourceOptions", "ChartOptions", "AnalysisOptions", + "Citation", + "CitationSource", + "CitationAnchor", }, ) @@ -51,6 +61,9 @@ class Context(proto.Message): etc) and system instructions (e.g., answer like a Pirate) can help the model understand the business context around a user question. + + Must be at most 250,000 bytes (approx. 250,000 + characters for English text). datasource_references (google.cloud.geminidataanalytics_v1alpha.types.DatasourceReferences): Required. Data sources that are available for answering the question. @@ -62,18 +75,25 @@ class Context(proto.Message): providing examples of relevant and commonly used SQL queries and their corresponding natural language queries optionally present. Currently - only used for BigQuery data sources. + only used for BigQuery data sources and + databases (alloydb, cloudsql, spanner) data + sources. looker_golden_queries (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.LookerGoldenQuery]): Optional. A list of golden queries, providing examples of relevant and commonly used Looker queries and their corresponding natural language - queries optionally present. + queries optionally present. Only supported for + Looker data sources. glossary_terms (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.GlossaryTerm]): Optional. Term definitions (currently, only - user authored) + user authored) Not supported for databases + (alloydb, cloudsql, spanner) data sources. schema_relationships (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.Context.SchemaRelationship]): Optional. Relationships between table schema, including referencing and referenced columns. + user_functions (google.cloud.geminidataanalytics_v1alpha.types.UserFunctions): + Optional. A collection of user functions to + be included in context. """ class SchemaRelationship(proto.Message): @@ -95,12 +115,12 @@ class SchemaRelationship(proto.Message): must correspond to a field at the same index in the ``left_schema_paths`` list. sources (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.Context.SchemaRelationship.Source]): - Sources which generated the schema relation - edge. + Optional. Sources which generated the schema + relation edge. confidence_score (float): - A confidence score for the suggested - relationship. Manually added edges have the - highest confidence score. + Optional. A confidence score for the + suggested relationship. Manually added edges + have the highest confidence score. """ class Source(proto.Enum): @@ -203,6 +223,75 @@ class SchemaPaths(proto.Message): number=9, message=SchemaRelationship, ) + user_functions: "UserFunctions" = proto.Field( + proto.MESSAGE, + number=10, + message="UserFunctions", + ) + + +class UserFunctions(proto.Message): + r"""A collection of user functions to be included in context. + + Attributes: + bq_routines (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.BigQueryRoutine]): + A list of BigQuery routines to include in the + context. + """ + + bq_routines: MutableSequence["BigQueryRoutine"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="BigQueryRoutine", + ) + + +class BigQueryRoutine(proto.Message): + r"""A reference to a BigQuery routine. + + Attributes: + routine_reference (google.cloud.geminidataanalytics_v1alpha.types.BigQueryRoutineReference): + The reference to the BigQuery routine. + description (str): + User override or addition to description, to + tell the agent when to use the UDF. + """ + + routine_reference: "BigQueryRoutineReference" = proto.Field( + proto.MESSAGE, + number=1, + message="BigQueryRoutineReference", + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + + +class BigQueryRoutineReference(proto.Message): + r"""A reference to a BigQuery routine. + + Attributes: + project_id (str): + The project ID of the routine. + dataset_id (str): + The dataset ID of the routine. + routine_id (str): + The routine ID of the routine. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + dataset_id: str = proto.Field( + proto.STRING, + number=2, + ) + routine_id: str = proto.Field( + proto.STRING, + number=3, + ) class ExampleQuery(proto.Message): @@ -218,13 +307,22 @@ class ExampleQuery(proto.Message): Optional. The SQL query that should be generated to answer the natural language question. For example: "SELECT COUNT(\*) FROM orders WHERE order_date BETWEEN '2024-01-01' - AND '2024-01-31'". + AND '2024-01-31'" + + Must be at most 50,000 bytes (approx. 50,000 characters). This field is a member of `oneof`_ ``query``. natural_language_question (str): Optional. A natural language question that a user might ask. For example: "How many orders - were placed last month?". + were placed last month?" + + Must be at most 2,000 bytes (approx. 2,000 + characters). + parameters (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.QueryParameter]): + Optional. The list of query parameters. Example: The + parameterized SQL query "SELECT \* FROM my_table WHERE id = + @id" can be matched with any value of id. """ sql_query: str = proto.Field( @@ -236,6 +334,96 @@ class ExampleQuery(proto.Message): proto.STRING, number=1, ) + parameters: MutableSequence["QueryParameter"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="QueryParameter", + ) + + +class QueryParameter(proto.Message): + r"""A query parameter message represents a parameter that can be + used to parameterize a SQL query. + + Attributes: + name (str): + Required. The name of the parameter reference + in the SQL query. + description (str): + Optional. The description of the parameter + that can be used by LLM to extract the parameter + value from the user question. + data_type (str): + Required. The data type of the parameter, e.g. "STRING", + "INT64", "DATE", etc. For valid values, see the `BigQuery + documentation `__. + This will be used to populate + google.cloud.bigquery.v2.QueryParameterType.type. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + data_type: str = proto.Field( + proto.STRING, + number=3, + ) + + +class MatchedQuery(proto.Message): + r"""A matched query message represents the agent having matched + one of the example queries supplied in context as being + applicable to the current question. It will also contain + additional info during the matching process. + + Attributes: + example_query (google.cloud.geminidataanalytics_v1alpha.types.ExampleQuery): + The query that was matched based on an + example query. + query_parameter_values (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.QueryParameterValues]): + The extracted values for the query + parameters. + """ + + example_query: "ExampleQuery" = proto.Field( + proto.MESSAGE, + number=1, + message="ExampleQuery", + ) + query_parameter_values: MutableSequence["QueryParameterValues"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=2, + message="QueryParameterValues", + ) + ) + + +class QueryParameterValues(proto.Message): + r"""A query parameter values message represents the values for + the query parameters that were extracted from the user question + by LLM, based on the example query. + + Attributes: + name (str): + Required. The name of the parameter. + value (str): + Required. The value of the parameter. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) class LookerGoldenQuery(proto.Message): @@ -247,7 +435,10 @@ class LookerGoldenQuery(proto.Message): natural_language_questions (MutableSequence[str]): Optional. Natural language questions that a user might ask. For example: "How many orders - were placed last month?". + were placed last month?" + + Must be at most 2,000 bytes per question + (approx. 2,000 characters). looker_query (google.cloud.geminidataanalytics_v1alpha.types.LookerQuery): Optional. The Looker Query corresponding to the natural language questions. @@ -264,6 +455,170 @@ class LookerGoldenQuery(proto.Message): ) +class DynamicField(proto.Message): + r"""A dynamic field in Looker (Custom Dimension, Custom Measure, + or Table Calculation). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + category (str): + Optional. The type of dynamic field: dimension, measure, + table_calculation. Looker can use the category type to + specify the name of the dynamic field. However, Looker + Conversational Analytics keeps the category separate from + the name of the dynamic field. For more details, see + https://docs.cloud.google.com/looker/docs/reference/param-lookml-dashboard-table-chart#dynamic_fields. + + This field is a member of `oneof`_ ``_category``. + name (str): + Optional. The name of the dynamic field in + LookML. + + This field is a member of `oneof`_ ``_name``. + label (str): + Optional. The label defines the display name + of the dynamic field. + + This field is a member of `oneof`_ ``_label``. + based_on (str): + Optional. For custom measures, this + identifies the measure the field is based on. + + This field is a member of `oneof`_ ``_based_on``. + type_ (str): + Optional. For custom measures, this + identifies the type of aggregation (e.g. sum). + + This field is a member of `oneof`_ ``_type``. + description (str): + Optional. Description of the dynamic field. + + This field is a member of `oneof`_ ``_description``. + expression (str): + Optional. Looker expression to create a table + calculation. + + This field is a member of `oneof`_ ``_expression``. + filter_expression (str): + Optional. Looker expression to filter a base + measure. + + This field is a member of `oneof`_ ``_filter_expression``. + value_format (str): + Optional. Value format for the dynamic field. + + This field is a member of `oneof`_ ``_value_format``. + value_format_name (str): + Optional. Value format name for the dynamic + field if using a default named format. + + This field is a member of `oneof`_ ``_value_format_name``. + calculation_type (str): + Optional. Calculation type for table calculations. Refer to + https://docs.cloud.google.com/looker/docs/reference/param-lookml-dashboard-table-chart#calculation_type + for all possible values depending on the ``category`` of + dynamic field. + + This field is a member of `oneof`_ ``_calculation_type``. + args (MutableSequence[str]): + Optional. Arguments for custom groups, custom bins, or + shortcut calculations. For more details, refer to + https://docs.cloud.google.com/looker/docs/reference/param-lookml-dashboard-table-chart#args_for_custom_groups + kind_hint (str): + Optional. Identifies whether the dynamic + field returns a dimension or measure. + + This field is a member of `oneof`_ ``_kind_hint``. + type_hint (str): + Optional. Identifies the data type the + dynamic field's expression should produce. + + This field is a member of `oneof`_ ``_type_hint``. + is_disabled (bool): + Optional. Whether the dynamic field is + disabled. + + This field is a member of `oneof`_ ``_is_disabled``. + """ + + category: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + name: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + label: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + based_on: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + type_: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + description: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + expression: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) + filter_expression: str = proto.Field( + proto.STRING, + number=8, + optional=True, + ) + value_format: str = proto.Field( + proto.STRING, + number=9, + optional=True, + ) + value_format_name: str = proto.Field( + proto.STRING, + number=10, + optional=True, + ) + calculation_type: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) + args: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=12, + ) + kind_hint: str = proto.Field( + proto.STRING, + number=13, + optional=True, + ) + type_hint: str = proto.Field( + proto.STRING, + number=14, + optional=True, + ) + is_disabled: bool = proto.Field( + proto.BOOL, + number=15, + optional=True, + ) + + class LookerQuery(proto.Message): r"""Looker Query Object `Looker API documentation `__. @@ -290,17 +645,39 @@ class LookerQuery(proto.Message): Optional. Limit in the query. This field is a member of `oneof`_ ``_limit``. + dynamic_fields (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.DynamicField]): + Optional. The dynamic fields used in the + query. + query_id (str): + Optional. The primary identifier for the query resource in + Looker, used for API operations. Maps to ``id`` (or + ``slug``) in the Looker API ``Query`` resource. + + This field is a member of `oneof`_ ``_query_id``. + client_id (str): + Optional. The short alphanumeric identifier for the query, + used for share links and Explore URLs (e.g., in the ``qid`` + parameter). Maps to ``client_id`` in the Looker API + ``Query`` resource. + + This field is a member of `oneof`_ ``_client_id``. """ class Filter(proto.Message): r"""A Looker query filter. + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: field (str): Required. The field to filter on. value (str): - Required. The value for the field to filter - on. + Optional. The value for the field to filter + on. Optional so we can preserve the default + value as an empty string, important to get a + valid and working Looker Explore url. + + This field is a member of `oneof`_ ``_value``. """ field: str = proto.Field( @@ -310,6 +687,7 @@ class Filter(proto.Message): value: str = proto.Field( proto.STRING, number=2, + optional=True, ) model: str = proto.Field( @@ -338,6 +716,21 @@ class Filter(proto.Message): number=6, optional=True, ) + dynamic_fields: MutableSequence["DynamicField"] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message="DynamicField", + ) + query_id: str = proto.Field( + proto.STRING, + number=10, + optional=True, + ) + client_id: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) class GlossaryTerm(proto.Message): @@ -347,13 +740,18 @@ class GlossaryTerm(proto.Message): display_name (str): Required. User friendly display name of the glossary term being defined. For example: "CTR", - "conversion rate", "pending". + "conversion rate", "pending" + + Must be at most 256 bytes. description (str): Required. The description or meaning of the term. For example: "Click-through rate", "The percentage of users who complete a desired action", "An order that is waiting to be - processed.". + processed." + + Must be at most 5,000 bytes (approx. 5,000 + characters). labels (MutableSequence[str]): Optional. A list of general purpose labels associated to this term. For example: ["click rate", "clickthrough", @@ -377,6 +775,8 @@ class GlossaryTerm(proto.Message): class ConversationOptions(proto.Message): r"""Options for the conversation. + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: chart (google.cloud.geminidataanalytics_v1alpha.types.ChartOptions): Optional. Options for chart generation. @@ -384,8 +784,30 @@ class ConversationOptions(proto.Message): Optional. Options for analysis. datasource (google.cloud.geminidataanalytics_v1alpha.types.DatasourceOptions): Optional. Options for datasources. + model (google.cloud.geminidataanalytics_v1alpha.types.ConversationOptions.Model): + Optional. The model to use for the agent + loop. + + This field is a member of `oneof`_ ``_model``. """ + class Model(proto.Enum): + r"""Allowed models for the agent/conversation. + + Values: + MODEL_UNSPECIFIED (0): + No model specified. The model may be set on + the chat request, or the default model will be + used. + LATEST_GA_MODEL (1): + Use the most up-to-date non-preview model. + This may constrain certain request level + settings. + """ + + MODEL_UNSPECIFIED = 0 + LATEST_GA_MODEL = 1 + chart: "ChartOptions" = proto.Field( proto.MESSAGE, number=1, @@ -401,6 +823,12 @@ class ConversationOptions(proto.Message): number=3, message="DatasourceOptions", ) + model: Model = proto.Field( + proto.ENUM, + number=6, + optional=True, + enum=Model, + ) class DatasourceOptions(proto.Message): @@ -509,4 +937,152 @@ class Python(proto.Message): ) +class Citation(proto.Message): + r"""Source attributions for content. + + Attributes: + sources (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.CitationSource]): + Output only. List of the sources being cited. + anchors (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.CitationAnchor]): + Output only. List of the anchors of the + citations. + """ + + sources: MutableSequence["CitationSource"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="CitationSource", + ) + anchors: MutableSequence["CitationAnchor"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="CitationAnchor", + ) + + +class CitationSource(proto.Message): + r"""The source of the citation. + + 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: + uri (str): + Output only. The uri used as the source, such + as a web grounding URL. + + This field is a member of `oneof`_ ``source_type``. + example_query (google.cloud.geminidataanalytics_v1alpha.types.ExampleQuery): + Output only. The example query used as the + source. + + This field is a member of `oneof`_ ``source_type``. + glossary_term (google.cloud.geminidataanalytics_v1alpha.types.GlossaryTerm): + Output only. The glossary term used as the + source. + + This field is a member of `oneof`_ ``source_type``. + id (str): + Output only. Unique identifier of the source. This ID is + service-generated and is unique within the scope of a single + ``Citation`` message. + title (str): + Output only. The title of the source. + """ + + uri: str = proto.Field( + proto.STRING, + number=3, + oneof="source_type", + ) + example_query: "ExampleQuery" = proto.Field( + proto.MESSAGE, + number=4, + oneof="source_type", + message="ExampleQuery", + ) + glossary_term: "GlossaryTerm" = proto.Field( + proto.MESSAGE, + number=5, + oneof="source_type", + message="GlossaryTerm", + ) + id: str = proto.Field( + proto.STRING, + number=1, + ) + title: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CitationAnchor(proto.Message): + r"""The anchor of the citation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + text_message_anchor (google.cloud.geminidataanalytics_v1alpha.types.CitationAnchor.TextMessageCitationAnchor): + Output only. Only set if the citation is for + a TextMessage. + + This field is a member of `oneof`_ ``anchor_type``. + """ + + class TextMessageCitationAnchor(proto.Message): + r"""Citation anchor within a TextMessage. + + Attributes: + part_index (int): + Output only. The 0-based index of the part + within the TextMessage.parts field. + start_offset_bytes (int): + Output only. The offset, measured in UTF-8 + bytes, within the part string where the citation + begins (inclusive). Example: For the text + "Hello, world" where "world" is cited, the start + offset bytes (inclusive) is 7 and the end offset + bytes (exclusive) is 12. + end_offset_bytes (int): + Output only. The offset, measured in UTF-8 + bytes, within the part string where the citation + ends (exclusive). Example: For the text "Hello, + world" where "world" is cited, the start offset + bytes (inclusive) is 7 and the end offset bytes + (exclusive) is 12. + source_ids (MutableSequence[str]): + Output only. The ids of the sources that are + cited. + """ + + part_index: int = proto.Field( + proto.INT32, + number=1, + ) + start_offset_bytes: int = proto.Field( + proto.INT32, + number=2, + ) + end_offset_bytes: int = proto.Field( + proto.INT32, + number=3, + ) + source_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + text_message_anchor: TextMessageCitationAnchor = proto.Field( + proto.MESSAGE, + number=1, + oneof="anchor_type", + message=TextMessageCitationAnchor, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/conversation.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/conversation.py index 77ed8631787f..985244b323dc 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/conversation.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/conversation.py @@ -17,6 +17,7 @@ from typing import MutableMapping, MutableSequence +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import proto # type: ignore @@ -25,6 +26,7 @@ manifest={ "Conversation", "CreateConversationRequest", + "UpdateConversationRequest", "GetConversationRequest", "ListConversationsRequest", "ListConversationsResponse", @@ -36,6 +38,8 @@ class Conversation(proto.Message): r"""Message for a conversation. + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: name (str): Optional. Identifier. The unique resource name of a @@ -67,6 +71,18 @@ class Conversation(proto.Message): that can be set by the client to tag a conversation (e.g. to filter conversations for specific surfaces/products). + title (str): + Optional. The display name for the + conversation (max 63 chars). + kms_key (str): + Optional. Customer managed encryption key (CMEK) to use for + encrypting the Conversation resources. Encryption will + happen at Titan layer, we will pass the KMS key to Titan. + + Format: + projects/{project_id}/locations/{location}/keyRings/{key_ring_name}/cryptoKeys/{key_name}. + + This field is a member of `oneof`_ ``_kms_key``. """ name: str = proto.Field( @@ -92,6 +108,15 @@ class Conversation(proto.Message): proto.STRING, number=9, ) + title: str = proto.Field( + proto.STRING, + number=6, + ) + kms_key: str = proto.Field( + proto.STRING, + number=10, + optional=True, + ) class CreateConversationRequest(proto.Message): @@ -136,6 +161,46 @@ class CreateConversationRequest(proto.Message): ) +class UpdateConversationRequest(proto.Message): + r"""Request for updating a conversation. + + Attributes: + conversation (google.cloud.geminidataanalytics_v1alpha.types.Conversation): + Required. The resource being updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Conversation resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields with non-default values present in the + request will be overwritten. If a wildcard mask is provided, + all fields will be overwritten. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + """ + + conversation: "Conversation" = proto.Field( + proto.MESSAGE, + number=1, + message="Conversation", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + class GetConversationRequest(proto.Message): r"""Request for getting a conversation based on parent and conversation id. @@ -160,11 +225,10 @@ class ListConversationsRequest(proto.Message): Required. Parent value for ListConversationsRequest. Format: ``projects/{project}/locations/{location}`` page_size (int): - Optional. Requested page size. Server may - return fewer items than requested. The max page - size is 100. All larger page sizes will be - coerced to 100. If unspecified, server will pick - 50 as an approperiate default. + Optional. Requested page size. Server may return fewer items + than requested. The max page size is ``100``. All larger + page sizes will be coerced to ``100``. If unspecified, + server will pick ``50`` as an appropriate default. page_token (str): Optional. A token identifying a page of results the server should return. diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/data_a2a_service.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/data_a2a_service.py new file mode 100644 index 000000000000..33f7587e0757 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/data_a2a_service.py @@ -0,0 +1,1539 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.geminidataanalytics.v1alpha", + manifest={ + "TaskState", + "Role", + "SendMessageConfiguration", + "A2ATask", + "TaskStatus", + "Part", + "FilePart", + "DataPart", + "A2AMessage", + "A2AArtifact", + "TaskStatusUpdateEvent", + "TaskArtifactUpdateEvent", + "PushNotificationConfig", + "AuthenticationInfo", + "AgentInterface", + "AgentCard", + "AgentProvider", + "AgentCapabilities", + "AgentExtension", + "AgentSkill", + "AgentCardSignature", + "StringList", + "Security", + "SecurityScheme", + "APIKeySecurityScheme", + "HTTPAuthSecurityScheme", + "OAuth2SecurityScheme", + "OpenIdConnectSecurityScheme", + "MutualTlsSecurityScheme", + "OAuthFlows", + "AuthorizationCodeOAuthFlow", + "ClientCredentialsOAuthFlow", + "ImplicitOAuthFlow", + "PasswordOAuthFlow", + "SendMessageRequest", + "GetAgentCardRequest", + "SendMessageResponse", + "StreamResponse", + }, +) + + +class TaskState(proto.Enum): + r"""The set of states a Task can be in. + + Values: + TASK_STATE_UNSPECIFIED (0): + Default unspecified task state. + TASK_STATE_SUBMITTED (1): + Represents the status that acknowledges a + task is created. + TASK_STATE_WORKING (2): + Represents the status that a task is + currently in progress. + TASK_STATE_COMPLETED (3): + Represents the status that a task is + completed. This is a terminal state. + TASK_STATE_FAILED (4): + Represents the status that a task has failed. + This is a terminal state. + TASK_STATE_CANCELLED (5): + Represents the status that a task was + cancelled before it finished. This is a terminal + state. + TASK_STATE_INPUT_REQUIRED (6): + Represents the status that the task requires + information to complete. This is an interrupted + state. + TASK_STATE_REJECTED (7): + Represents the status that a task has been + rejected by the agent. This is a terminal state. + TASK_STATE_AUTH_REQUIRED (8): + Represents the state that some authentication + is needed from the upstream client. + """ + + TASK_STATE_UNSPECIFIED = 0 + TASK_STATE_SUBMITTED = 1 + TASK_STATE_WORKING = 2 + TASK_STATE_COMPLETED = 3 + TASK_STATE_FAILED = 4 + TASK_STATE_CANCELLED = 5 + TASK_STATE_INPUT_REQUIRED = 6 + TASK_STATE_REJECTED = 7 + TASK_STATE_AUTH_REQUIRED = 8 + + +class Role(proto.Enum): + r"""Role indicates the sender of a message. + + Values: + ROLE_UNSPECIFIED (0): + Default unspecified role. + ROLE_USER (1): + USER role refers to communication from the + client to the server. + ROLE_AGENT (2): + AGENT role refers to communication from the + server to the client. + """ + + ROLE_UNSPECIFIED = 0 + ROLE_USER = 1 + ROLE_AGENT = 2 + + +class SendMessageConfiguration(proto.Message): + r"""Configuration of a send message request. + + Attributes: + accepted_output_modes (MutableSequence[str]): + Optional. The output modes that the agent is + expected to respond with. + push_notification (google.cloud.geminidataanalytics_v1alpha.types.PushNotificationConfig): + Optional. A configuration of a webhook that + can be used to receive updates. + history_length (int): + Optional. The maximum number of messages to + include in the history. If 0, the history will + be unlimited. + blocking (bool): + Optional. If true, the message will be + blocking until the task is completed. If false, + the task will be returned immediately. + """ + + accepted_output_modes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + push_notification: "PushNotificationConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="PushNotificationConfig", + ) + history_length: int = proto.Field( + proto.INT32, + number=3, + ) + blocking: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class A2ATask(proto.Message): + r"""A2ATask is the core unit of action for A2A. It has a current + status and when results are created for the task they are stored + in the artifact. If there are multiple turns for a task, these + are stored in history. + + Attributes: + id (str): + Optional. Unique identifier (e.g. UUID) for + the task, generated by the server for a new + task. + context_id (str): + Optional. Unique identifier (e.g. UUID) for + the contextual collection of interactions (tasks + and messages). Created by the A2A server. + status (google.cloud.geminidataanalytics_v1alpha.types.TaskStatus): + Optional. The current status of a Task, + including state and a message. + artifacts (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.A2AArtifact]): + Optional. A set of output artifacts for a + Task. + history (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.A2AMessage]): + Optional. The history of interactions from a + task. + metadata (google.protobuf.struct_pb2.Struct): + Optional. A key/value object to store custom + metadata about a task. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + context_id: str = proto.Field( + proto.STRING, + number=2, + ) + status: "TaskStatus" = proto.Field( + proto.MESSAGE, + number=3, + message="TaskStatus", + ) + artifacts: MutableSequence["A2AArtifact"] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="A2AArtifact", + ) + history: MutableSequence["A2AMessage"] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="A2AMessage", + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + + +class TaskStatus(proto.Message): + r"""A container for the status of a task. + + Attributes: + state (google.cloud.geminidataanalytics_v1alpha.types.TaskState): + Output only. The current state of this task. + update (google.cloud.geminidataanalytics_v1alpha.types.A2AMessage): + Optional. A message associated with the + status. + timestamp (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the status was + recorded. + """ + + state: "TaskState" = proto.Field( + proto.ENUM, + number=1, + enum="TaskState", + ) + update: "A2AMessage" = proto.Field( + proto.MESSAGE, + number=2, + message="A2AMessage", + ) + timestamp: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class Part(proto.Message): + r"""Part represents a container for a section of communication + content. Parts can be purely textual, some sort of file (image, + video, etc) or a structured data blob (i.e. JSON). + + 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: + text (str): + Plain text content. + + This field is a member of `oneof`_ ``part``. + file (google.cloud.geminidataanalytics_v1alpha.types.FilePart): + File content payload. + + This field is a member of `oneof`_ ``part``. + data (google.cloud.geminidataanalytics_v1alpha.types.DataPart): + Structured data content payload. + + This field is a member of `oneof`_ ``part``. + metadata (google.protobuf.struct_pb2.Struct): + Optional. Metadata associated with the part. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + oneof="part", + ) + file: "FilePart" = proto.Field( + proto.MESSAGE, + number=2, + oneof="part", + message="FilePart", + ) + data: "DataPart" = proto.Field( + proto.MESSAGE, + number=3, + oneof="part", + message="DataPart", + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + + +class FilePart(proto.Message): + r"""FilePart represents the different ways files can be provided. + + 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: + file_with_uri (str): + The URI pointing to the file. + + This field is a member of `oneof`_ ``file``. + file_with_bytes (bytes): + The raw bytes of the file. + + This field is a member of `oneof`_ ``file``. + mime_type (str): + Optional. The MIME type of the file. + name (str): + Optional. The name of the file. + """ + + file_with_uri: str = proto.Field( + proto.STRING, + number=1, + oneof="file", + ) + file_with_bytes: bytes = proto.Field( + proto.BYTES, + number=2, + oneof="file", + ) + mime_type: str = proto.Field( + proto.STRING, + number=3, + ) + name: str = proto.Field( + proto.STRING, + number=4, + ) + + +class DataPart(proto.Message): + r"""DataPart represents a structured blob. This is most commonly + a JSON payload. + + Attributes: + data (google.protobuf.struct_pb2.Struct): + Optional. The structured data payload. + """ + + data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=1, + message=struct_pb2.Struct, + ) + + +class A2AMessage(proto.Message): + r"""A2AMessage is one unit of communication between client and + server. + + Attributes: + message_id (str): + Optional. The unique identifier (e.g. UUID) + of the message. + context_id (str): + Optional. The context id of the message. + task_id (str): + Optional. The task id of the message. + role (google.cloud.geminidataanalytics_v1alpha.types.Role): + Optional. A role for the message. + content (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.Part]): + Optional. Content is the container of the + message content. + metadata (google.protobuf.struct_pb2.Struct): + Optional. Any optional metadata to provide + along with the message. + extensions (MutableSequence[str]): + Optional. The URIs of extensions that are + present or contributed to this Message. + """ + + message_id: str = proto.Field( + proto.STRING, + number=1, + ) + context_id: str = proto.Field( + proto.STRING, + number=2, + ) + task_id: str = proto.Field( + proto.STRING, + number=3, + ) + role: "Role" = proto.Field( + proto.ENUM, + number=4, + enum="Role", + ) + content: MutableSequence["Part"] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="Part", + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + extensions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + +class A2AArtifact(proto.Message): + r"""A2AArtifact is the container for task completed results. + + Attributes: + artifact_id (str): + Optional. Unique identifier (e.g. UUID) for + the artifact. + name (str): + Optional. A human readable name for the + artifact. + description (str): + Optional. A human readable description of the + artifact, optional. + parts (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.Part]): + Optional. The content of the artifact. + metadata (google.protobuf.struct_pb2.Struct): + Optional. Optional metadata included with the + artifact. + extensions (MutableSequence[str]): + Optional. The URIs of extensions that are + present or contributed to this Artifact. + """ + + artifact_id: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + description: str = proto.Field( + proto.STRING, + number=4, + ) + parts: MutableSequence["Part"] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="Part", + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + extensions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + +class TaskStatusUpdateEvent(proto.Message): + r"""TaskStatusUpdateEvent is a delta event on a task indicating + that a task has changed. + + Attributes: + task_id (str): + Optional. The id of the task that is changed. + context_id (str): + Optional. The id of the context that the task + belongs to. + status (google.cloud.geminidataanalytics_v1alpha.types.TaskStatus): + Optional. The new status of the task. + final (bool): + Optional. Whether this is the last status + update expected for this task. + metadata (google.protobuf.struct_pb2.Struct): + Optional. Optional metadata to associate with + the task update. + """ + + task_id: str = proto.Field( + proto.STRING, + number=1, + ) + context_id: str = proto.Field( + proto.STRING, + number=2, + ) + status: "TaskStatus" = proto.Field( + proto.MESSAGE, + number=3, + message="TaskStatus", + ) + final: bool = proto.Field( + proto.BOOL, + number=4, + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=5, + message=struct_pb2.Struct, + ) + + +class TaskArtifactUpdateEvent(proto.Message): + r"""TaskArtifactUpdateEvent represents a task delta where an + artifact has been generated. + + Attributes: + task_id (str): + Optional. The id of the task for this + artifact. + context_id (str): + Optional. The id of the context that this + task belongs to. + artifact (google.cloud.geminidataanalytics_v1alpha.types.A2AArtifact): + Optional. The artifact itself. + append (bool): + Optional. Whether this should be appended to + a prior one produced. + last_chunk (bool): + Optional. Whether this represents the last + part of an artifact. + metadata (google.protobuf.struct_pb2.Struct): + Optional. Optional metadata associated with + the artifact update. + """ + + task_id: str = proto.Field( + proto.STRING, + number=1, + ) + context_id: str = proto.Field( + proto.STRING, + number=2, + ) + artifact: "A2AArtifact" = proto.Field( + proto.MESSAGE, + number=3, + message="A2AArtifact", + ) + append: bool = proto.Field( + proto.BOOL, + number=4, + ) + last_chunk: bool = proto.Field( + proto.BOOL, + number=5, + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + + +class PushNotificationConfig(proto.Message): + r"""Configuration for setting up push notifications for task + updates. + + Attributes: + id (str): + Optional. A unique identifier (e.g. UUID) for + this push notification. + url (str): + Optional. Url to send the notification to. + token (str): + Optional. Token unique for this task/session. + authentication (google.cloud.geminidataanalytics_v1alpha.types.AuthenticationInfo): + Optional. Information about the + authentication to send with the notification. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + url: str = proto.Field( + proto.STRING, + number=2, + ) + token: str = proto.Field( + proto.STRING, + number=3, + ) + authentication: "AuthenticationInfo" = proto.Field( + proto.MESSAGE, + number=4, + message="AuthenticationInfo", + ) + + +class AuthenticationInfo(proto.Message): + r"""Defines authentication details, used for push notifications. + + Attributes: + schemes (MutableSequence[str]): + Optional. Supported authentication schemes - + e.g. Basic, Bearer, etc. + credentials (str): + Optional. Optional credentials. + """ + + schemes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + credentials: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AgentInterface(proto.Message): + r"""Defines additional transport information for the agent. + + Attributes: + url (str): + Optional. The url this interface is found at. + transport (str): + Optional. The transport supported at this + url. + tenant (str): + Optional. Tenant to be set in the request + when calling the agent. + """ + + url: str = proto.Field( + proto.STRING, + number=1, + ) + transport: str = proto.Field( + proto.STRING, + number=2, + ) + tenant: str = proto.Field( + proto.STRING, + number=3, + ) + + +class AgentCard(proto.Message): + r"""AgentCard conveys key information about an agent. + + Attributes: + protocol_version (str): + Optional. The version of the A2A protocol + this agent supports. + name (str): + Optional. A human readable name for the + agent. + description (str): + Optional. A description of the agent's domain + of action/solution space. + url (str): + Optional. A URL to the address the agent is + hosted at. + preferred_transport (str): + Optional. The transport of the preferred + endpoint. If empty, defaults to JSONRPC. + additional_interfaces (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.AgentInterface]): + Optional. Announcement of additional + supported transports. + provider (google.cloud.geminidataanalytics_v1alpha.types.AgentProvider): + Optional. The service provider of the agent. + version (str): + Optional. The version of the agent. + documentation_url (str): + Optional. A url to provide additional + documentation about the agent. + capabilities (google.cloud.geminidataanalytics_v1alpha.types.AgentCapabilities): + Optional. A2A Capability set supported by the + agent. + security_schemes (MutableMapping[str, google.cloud.geminidataanalytics_v1alpha.types.SecurityScheme]): + The security scheme details used for + authenticating with this agent. + security (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.Security]): + Security requirements for contacting the + agent. + default_input_modes (MutableSequence[str]): + Optional. The set of interaction modes that + the agent supports across all skills. + default_output_modes (MutableSequence[str]): + Optional. The mime types supported as outputs + from this agent. + skills (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.AgentSkill]): + Optional. Skills represent a unit of ability + an agent can perform. + supports_authenticated_extended_card (bool): + Optional. Whether the agent supports + providing an extended agent card when the user + is authenticated. + signatures (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.AgentCardSignature]): + Optional. JSON Web Signatures computed for + this AgentCard. + icon_url (str): + Optional. An optional URL to an icon for the + agent. + """ + + protocol_version: str = proto.Field( + proto.STRING, + number=16, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + url: str = proto.Field( + proto.STRING, + number=3, + ) + preferred_transport: str = proto.Field( + proto.STRING, + number=14, + ) + additional_interfaces: MutableSequence["AgentInterface"] = proto.RepeatedField( + proto.MESSAGE, + number=15, + message="AgentInterface", + ) + provider: "AgentProvider" = proto.Field( + proto.MESSAGE, + number=4, + message="AgentProvider", + ) + version: str = proto.Field( + proto.STRING, + number=5, + ) + documentation_url: str = proto.Field( + proto.STRING, + number=6, + ) + capabilities: "AgentCapabilities" = proto.Field( + proto.MESSAGE, + number=7, + message="AgentCapabilities", + ) + security_schemes: MutableMapping[str, "SecurityScheme"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=8, + message="SecurityScheme", + ) + security: MutableSequence["Security"] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message="Security", + ) + default_input_modes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + default_output_modes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=11, + ) + skills: MutableSequence["AgentSkill"] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message="AgentSkill", + ) + supports_authenticated_extended_card: bool = proto.Field( + proto.BOOL, + number=13, + ) + signatures: MutableSequence["AgentCardSignature"] = proto.RepeatedField( + proto.MESSAGE, + number=17, + message="AgentCardSignature", + ) + icon_url: str = proto.Field( + proto.STRING, + number=18, + ) + + +class AgentProvider(proto.Message): + r"""Represents information about the service provider of an + agent. + + Attributes: + url (str): + Optional. The provider's reference url. + organization (str): + Optional. The provider's organization name. + """ + + url: str = proto.Field( + proto.STRING, + number=1, + ) + organization: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AgentCapabilities(proto.Message): + r"""Defines the A2A feature set supported by the agent. + + Attributes: + streaming (bool): + Optional. If the agent will support streaming + responses. + push_notifications (bool): + Optional. If the agent can send push + notifications to the client's webhook. + extensions (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.AgentExtension]): + Optional. Extensions supported by this agent. + """ + + streaming: bool = proto.Field( + proto.BOOL, + number=1, + ) + push_notifications: bool = proto.Field( + proto.BOOL, + number=2, + ) + extensions: MutableSequence["AgentExtension"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="AgentExtension", + ) + + +class AgentExtension(proto.Message): + r"""A declaration of an extension supported by an Agent. + + Attributes: + uri (str): + Optional. The URI of the extension. + description (str): + Optional. A description of how this agent + uses this extension. + required (bool): + Optional. Whether the client must follow + specific requirements of the extension. + params (google.protobuf.struct_pb2.Struct): + Optional. Optional configuration for the + extension. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + required: bool = proto.Field( + proto.BOOL, + number=3, + ) + params: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + + +class AgentSkill(proto.Message): + r"""AgentSkill represents a unit of action/solution that the + agent can perform. + + Attributes: + id (str): + Optional. Unique identifier of the skill + within this agent. + name (str): + Optional. A human readable name for the + skill. + description (str): + Optional. A human readable description of the + skill details and behaviors. + tags (MutableSequence[str]): + Optional. A set of tags for the skill to + enhance categorization/utilization. + examples (MutableSequence[str]): + Optional. A set of example queries that this + skill is designed to address. + input_modes (MutableSequence[str]): + Optional. Possible input modalities + supported. + output_modes (MutableSequence[str]): + Optional. Possible output modalities + produced. + security (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.Security]): + Security schemes necessary for the agent to + leverage this skill. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + examples: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + input_modes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + output_modes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + security: MutableSequence["Security"] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message="Security", + ) + + +class AgentCardSignature(proto.Message): + r"""AgentCardSignature represents a JWS signature of an + AgentCard. + + Attributes: + protected (str): + Required. The protected JWS header for the + signature. Base64url-encoded. + signature (str): + Required. The computed signature, + base64url-encoded. + header (google.protobuf.struct_pb2.Struct): + Optional. The unprotected JWS header values. + """ + + protected: str = proto.Field( + proto.STRING, + number=1, + ) + signature: str = proto.Field( + proto.STRING, + number=2, + ) + header: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + + +class StringList(proto.Message): + r"""StringList is a wrapper for a repeated list of strings. + + Attributes: + list_ (MutableSequence[str]): + The list of strings. + """ + + list_: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class Security(proto.Message): + r"""Security requirements for contacting the agent. + + Attributes: + schemes (MutableMapping[str, google.cloud.geminidataanalytics_v1alpha.types.StringList]): + Map of scheme names to lists of scopes or + configurations. + """ + + schemes: MutableMapping[str, "StringList"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message="StringList", + ) + + +class SecurityScheme(proto.Message): + r"""SecurityScheme defines a security scheme for contacting the + agent. + + 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: + api_key_security_scheme (google.cloud.geminidataanalytics_v1alpha.types.APIKeySecurityScheme): + API key security scheme. + + This field is a member of `oneof`_ ``scheme``. + http_auth_security_scheme (google.cloud.geminidataanalytics_v1alpha.types.HTTPAuthSecurityScheme): + HTTP authentication security scheme. + + This field is a member of `oneof`_ ``scheme``. + oauth2_security_scheme (google.cloud.geminidataanalytics_v1alpha.types.OAuth2SecurityScheme): + OAuth2 security scheme. + + This field is a member of `oneof`_ ``scheme``. + open_id_connect_security_scheme (google.cloud.geminidataanalytics_v1alpha.types.OpenIdConnectSecurityScheme): + OpenID Connect security scheme. + + This field is a member of `oneof`_ ``scheme``. + mtls_security_scheme (google.cloud.geminidataanalytics_v1alpha.types.MutualTlsSecurityScheme): + Mutual TLS security scheme. + + This field is a member of `oneof`_ ``scheme``. + """ + + api_key_security_scheme: "APIKeySecurityScheme" = proto.Field( + proto.MESSAGE, + number=1, + oneof="scheme", + message="APIKeySecurityScheme", + ) + http_auth_security_scheme: "HTTPAuthSecurityScheme" = proto.Field( + proto.MESSAGE, + number=2, + oneof="scheme", + message="HTTPAuthSecurityScheme", + ) + oauth2_security_scheme: "OAuth2SecurityScheme" = proto.Field( + proto.MESSAGE, + number=3, + oneof="scheme", + message="OAuth2SecurityScheme", + ) + open_id_connect_security_scheme: "OpenIdConnectSecurityScheme" = proto.Field( + proto.MESSAGE, + number=4, + oneof="scheme", + message="OpenIdConnectSecurityScheme", + ) + mtls_security_scheme: "MutualTlsSecurityScheme" = proto.Field( + proto.MESSAGE, + number=5, + oneof="scheme", + message="MutualTlsSecurityScheme", + ) + + +class APIKeySecurityScheme(proto.Message): + r"""APIKeySecurityScheme defines an API key security scheme. + + Attributes: + description (str): + Optional. Description of this security + scheme. + location (str): + Optional. Location of the API key, valid + values are "query", "header", or "cookie". + name (str): + Optional. Name of the header, query or cookie + parameter to be used. + """ + + description: str = proto.Field( + proto.STRING, + number=1, + ) + location: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + +class HTTPAuthSecurityScheme(proto.Message): + r"""HTTPAuthSecurityScheme defines an HTTP authentication + security scheme. + + Attributes: + description (str): + Optional. Description of this security + scheme. + scheme (str): + Optional. The name of the HTTP Authentication + scheme to be used in the Authorization header. + bearer_format (str): + Optional. A hint to the client to identify + how the bearer token is formatted. + """ + + description: str = proto.Field( + proto.STRING, + number=1, + ) + scheme: str = proto.Field( + proto.STRING, + number=2, + ) + bearer_format: str = proto.Field( + proto.STRING, + number=3, + ) + + +class OAuth2SecurityScheme(proto.Message): + r"""OAuth2SecurityScheme defines an OAuth2 security scheme. + + Attributes: + description (str): + Optional. Description of this security + scheme. + flows (google.cloud.geminidataanalytics_v1alpha.types.OAuthFlows): + Optional. An object containing configuration + information for the flow types supported. + oauth2_metadata_url (str): + Optional. URL to the oauth2 authorization + server metadata. + """ + + description: str = proto.Field( + proto.STRING, + number=1, + ) + flows: "OAuthFlows" = proto.Field( + proto.MESSAGE, + number=2, + message="OAuthFlows", + ) + oauth2_metadata_url: str = proto.Field( + proto.STRING, + number=3, + ) + + +class OpenIdConnectSecurityScheme(proto.Message): + r"""OpenIdConnectSecurityScheme defines an OpenID Connect + security scheme. + + Attributes: + description (str): + Optional. Description of this security + scheme. + open_id_connect_url (str): + Optional. Well-known URL to discover the + OpenID Connect provider metadata. + """ + + description: str = proto.Field( + proto.STRING, + number=1, + ) + open_id_connect_url: str = proto.Field( + proto.STRING, + number=2, + ) + + +class MutualTlsSecurityScheme(proto.Message): + r"""MutualTlsSecurityScheme defines a Mutual TLS security scheme. + + Attributes: + description (str): + Optional. Description of this security + scheme. + """ + + description: str = proto.Field( + proto.STRING, + number=1, + ) + + +class OAuthFlows(proto.Message): + r"""OAuthFlows contains configuration information for supported + OAuth flows. + + 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: + authorization_code (google.cloud.geminidataanalytics_v1alpha.types.AuthorizationCodeOAuthFlow): + Authorization code flow. + + This field is a member of `oneof`_ ``flow``. + client_credentials (google.cloud.geminidataanalytics_v1alpha.types.ClientCredentialsOAuthFlow): + Client credentials flow. + + This field is a member of `oneof`_ ``flow``. + implicit (google.cloud.geminidataanalytics_v1alpha.types.ImplicitOAuthFlow): + Implicit flow. + + This field is a member of `oneof`_ ``flow``. + password (google.cloud.geminidataanalytics_v1alpha.types.PasswordOAuthFlow): + Resource owner password credentials flow. + + This field is a member of `oneof`_ ``flow``. + """ + + authorization_code: "AuthorizationCodeOAuthFlow" = proto.Field( + proto.MESSAGE, + number=1, + oneof="flow", + message="AuthorizationCodeOAuthFlow", + ) + client_credentials: "ClientCredentialsOAuthFlow" = proto.Field( + proto.MESSAGE, + number=2, + oneof="flow", + message="ClientCredentialsOAuthFlow", + ) + implicit: "ImplicitOAuthFlow" = proto.Field( + proto.MESSAGE, + number=3, + oneof="flow", + message="ImplicitOAuthFlow", + ) + password: "PasswordOAuthFlow" = proto.Field( + proto.MESSAGE, + number=4, + oneof="flow", + message="PasswordOAuthFlow", + ) + + +class AuthorizationCodeOAuthFlow(proto.Message): + r"""AuthorizationCodeOAuthFlow defines an authorization code + OAuth flow. + + Attributes: + authorization_url (str): + Optional. The authorization URL to be used + for this flow. + token_url (str): + Optional. The token URL to be used for this + flow. + refresh_url (str): + Optional. The URL to be used for obtaining + refresh tokens. + scopes (MutableMapping[str, str]): + The available scopes for the OAuth2 security + scheme. + """ + + authorization_url: str = proto.Field( + proto.STRING, + number=1, + ) + token_url: str = proto.Field( + proto.STRING, + number=2, + ) + refresh_url: str = proto.Field( + proto.STRING, + number=3, + ) + scopes: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + + +class ClientCredentialsOAuthFlow(proto.Message): + r"""ClientCredentialsOAuthFlow defines a client credentials OAuth + flow. + + Attributes: + token_url (str): + Optional. The token URL to be used for this + flow. + refresh_url (str): + Optional. The URL to be used for obtaining + refresh tokens. + scopes (MutableMapping[str, str]): + The available scopes for the OAuth2 security + scheme. + """ + + token_url: str = proto.Field( + proto.STRING, + number=1, + ) + refresh_url: str = proto.Field( + proto.STRING, + number=2, + ) + scopes: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + + +class ImplicitOAuthFlow(proto.Message): + r"""ImplicitOAuthFlow defines an implicit OAuth flow. + + Attributes: + authorization_url (str): + Optional. The authorization URL to be used + for this flow. + refresh_url (str): + Optional. The URL to be used for obtaining + refresh tokens. + scopes (MutableMapping[str, str]): + The available scopes for the OAuth2 security + scheme. + """ + + authorization_url: str = proto.Field( + proto.STRING, + number=1, + ) + refresh_url: str = proto.Field( + proto.STRING, + number=2, + ) + scopes: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + + +class PasswordOAuthFlow(proto.Message): + r"""PasswordOAuthFlow defines a password OAuth flow. + + Attributes: + token_url (str): + Optional. The token URL to be used for this + flow. + refresh_url (str): + Optional. The URL to be used for obtaining + refresh tokens. + scopes (MutableMapping[str, str]): + The available scopes for the OAuth2 security + scheme. + """ + + token_url: str = proto.Field( + proto.STRING, + number=1, + ) + refresh_url: str = proto.Field( + proto.STRING, + number=2, + ) + scopes: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + + +class SendMessageRequest(proto.Message): + r"""Request message for SendMessage and SendStreamingMessage. + + Attributes: + message (google.cloud.geminidataanalytics_v1alpha.types.A2AMessage): + Required. The message to send to the agent. + configuration (google.cloud.geminidataanalytics_v1alpha.types.SendMessageConfiguration): + Optional. Configuration for the send request. + metadata (google.protobuf.struct_pb2.Struct): + Optional. Optional metadata for the request. + tenant (str): + Optional. Optional tenant, provided as a path + parameter. + """ + + message: "A2AMessage" = proto.Field( + proto.MESSAGE, + number=1, + message="A2AMessage", + ) + configuration: "SendMessageConfiguration" = proto.Field( + proto.MESSAGE, + number=2, + message="SendMessageConfiguration", + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + tenant: str = proto.Field( + proto.STRING, + number=4, + ) + + +class GetAgentCardRequest(proto.Message): + r"""Request message for GetAgentCard. + + Attributes: + tenant (str): + Optional. Optional tenant, provided as a path + parameter. + """ + + tenant: str = proto.Field( + proto.STRING, + number=1, + ) + + +class SendMessageResponse(proto.Message): + r"""Response message for SendMessage. + + 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: + task (google.cloud.geminidataanalytics_v1alpha.types.A2ATask): + Completed task. + + This field is a member of `oneof`_ ``payload``. + msg (google.cloud.geminidataanalytics_v1alpha.types.A2AMessage): + Single message response. + + This field is a member of `oneof`_ ``payload``. + """ + + task: "A2ATask" = proto.Field( + proto.MESSAGE, + number=1, + oneof="payload", + message="A2ATask", + ) + msg: "A2AMessage" = proto.Field( + proto.MESSAGE, + number=2, + oneof="payload", + message="A2AMessage", + ) + + +class StreamResponse(proto.Message): + r"""The stream response for a message. + + 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: + task (google.cloud.geminidataanalytics_v1alpha.types.A2ATask): + Completed task event. + + This field is a member of `oneof`_ ``payload``. + msg (google.cloud.geminidataanalytics_v1alpha.types.A2AMessage): + Message event. + + This field is a member of `oneof`_ ``payload``. + status_update (google.cloud.geminidataanalytics_v1alpha.types.TaskStatusUpdateEvent): + Task status update event. + + This field is a member of `oneof`_ ``payload``. + artifact_update (google.cloud.geminidataanalytics_v1alpha.types.TaskArtifactUpdateEvent): + Task artifact update event. + + This field is a member of `oneof`_ ``payload``. + """ + + task: "A2ATask" = proto.Field( + proto.MESSAGE, + number=1, + oneof="payload", + message="A2ATask", + ) + msg: "A2AMessage" = proto.Field( + proto.MESSAGE, + number=2, + oneof="payload", + message="A2AMessage", + ) + status_update: "TaskStatusUpdateEvent" = proto.Field( + proto.MESSAGE, + number=3, + oneof="payload", + message="TaskStatusUpdateEvent", + ) + artifact_update: "TaskArtifactUpdateEvent" = proto.Field( + proto.MESSAGE, + number=4, + oneof="payload", + message="TaskArtifactUpdateEvent", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/data_agent.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/data_agent.py index f75c6cf54380..928442a0735a 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/data_agent.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/data_agent.py @@ -23,6 +23,7 @@ from google.cloud.geminidataanalytics_v1alpha.types import ( data_analytics_agent as gcg_data_analytics_agent, ) +from google.cloud.geminidataanalytics_v1alpha.types import datasource __protobuf__ = proto.module( package="google.cloud.geminidataanalytics.v1alpha", @@ -84,6 +85,75 @@ class DataAgent(proto.Message): Output only. Timestamp in UTC of when this data agent is considered expired. This is *always* provided on output, regardless of what was sent on input. + kms_key (str): + Optional. Customer managed encryption key (CMEK) to use for + encrypting the DataAgent resources. Cloud KMS CryptoKeys + must reside in the same location as the DataAgent. The + expected format is + ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + + This field is a member of `oneof`_ ``_kms_key``. + bigquery_agent_analytics_enabled (bool): + Optional. Controls whether BigQuery Agent Analytics trace + logging is enabled for the agent. + + BigQuery Agent Analytics is in Preview and is delivered to + enrolled projects only. In a project that is not enrolled + this field is accepted and stored, but no trace rows are + written and no error is returned. + + Trace logging is additionally suppressed for the entire + turn, without error, when any table in the agent's + datasource carries row-level security, column-level security + or policy tags. It is also suppressed when that + determination cannot be made, for example when the caller + lacks permission to list a table's row access policies. + + Trace rows are written only when this is ``true`` and + ``bigquery_agent_analytics_table`` is set. On a BigQuery + agent, enabling this without a table has no effect: no table + is created for the agent and no rows are written. On an + agent whose datasource is not BigQuery, ``CreateDataAgent`` + rejects either field with ``INVALID_ARGUMENT``. + + This setting is independent of the project-level BigQuery + Agent Analytics setting configured through + ``SetAgentOpsObservability``. An agent does not inherit that + setting. + + This field is a member of `oneof`_ ``_bigquery_agent_analytics_enabled``. + bigquery_agent_analytics_table (google.cloud.geminidataanalytics_v1alpha.types.BigQueryTableReference): + Optional. The BigQuery table that BigQuery Agent Analytics + trace rows are written to. Has no effect unless + ``bigquery_agent_analytics_enabled`` is ``true``. The + Preview enrollment described on that field applies here too. + + The trace table is validated when it is set on + ``CreateDataAgent``, or when it is included in the + ``update_mask`` of an ``UpdateDataAgent`` call. The + following are rejected with ``INVALID_ARGUMENT``: + + - The table must belong to the same project as the agent. + - The agent's datasource must be BigQuery. BigQuery Agent + Analytics is not supported for Looker, Looker Studio or + AlloyDB agents. + + These are validated against the agent as sent in the + request. An agent that carries no datasource is not + validated, and an agent switched to a non-BigQuery + datasource is not re-validated; in the latter case no trace + rows are written. + + The destination dataset must already exist and must grant + write access to the project's Gemini Data Analytics service + agent, whose address is + ``service-PROJECT_NUMBER@gcp-sa-geminidataanalytics.iam.gserviceaccount.com`` + (that grant is not performed on your behalf). Without it the + agent answers normally and no trace rows are written. + + Changing the table on an existing agent affects subsequent + turns only. Rows already written to the previous table are + left in place. """ data_analytics_agent: gcg_data_analytics_agent.DataAnalyticsAgent = proto.Field( @@ -129,6 +199,21 @@ class DataAgent(proto.Message): number=13, message=timestamp_pb2.Timestamp, ) + kms_key: str = proto.Field( + proto.STRING, + number=14, + optional=True, + ) + bigquery_agent_analytics_enabled: bool = proto.Field( + proto.BOOL, + number=18, + optional=True, + ) + bigquery_agent_analytics_table: datasource.BigQueryTableReference = proto.Field( + proto.MESSAGE, + number=19, + message=datasource.BigQueryTableReference, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/data_agent_service.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/data_agent_service.py index c6ccfa3246c5..0aa9ed299759 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/data_agent_service.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/data_agent_service.py @@ -35,6 +35,11 @@ "UpdateDataAgentRequest", "DeleteDataAgentRequest", "OperationMetadata", + "SetAgentOpsObservabilityRequest", + "SetAgentOpsObservabilityResponse", + "SetAgentOpsObservabilityMetadata", + "RetrieveAgentOpsObservabilityRequest", + "RetrieveAgentOpsObservabilityResponse", }, ) @@ -68,6 +73,9 @@ class ListDataAgentsRequest(proto.Message): Optional. If true, the list results will include soft-deleted DataAgents. Defaults to false. + creator_filter (google.cloud.geminidataanalytics_v1alpha.types.ListAccessibleDataAgentsRequest.CreatorFilter): + Optional. Filter for the creator of the + agent. """ parent: str = proto.Field( @@ -94,6 +102,11 @@ class ListDataAgentsRequest(proto.Message): proto.BOOL, number=6, ) + creator_filter: "ListAccessibleDataAgentsRequest.CreatorFilter" = proto.Field( + proto.ENUM, + number=8, + enum="ListAccessibleDataAgentsRequest.CreatorFilter", + ) class ListDataAgentsResponse(proto.Message): @@ -469,4 +482,159 @@ class OperationMetadata(proto.Message): ) +class SetAgentOpsObservabilityRequest(proto.Message): + r"""Request for SetAgentOpsObservability. + + Attributes: + parent (str): + Required. Parent value for + SetAgentOpsObservabilityRequest. Format: + projects/{project}/locations/{location} + telemetry_enabled (bool): + Optional. Whether to enable or disable AgentOps + observability. When update_mask is provided, this field is + ignored unless specified in the mask. + data_source_type (str): + Required. The data source type for which to + set observability settings. Examples: + "bigquery", "looker". + bqaa_enabled (bool): + Optional. Whether BigQuery Agent Analytics is enabled. Note: + An explicit ``update_mask`` containing "bqaa_enabled" is + required to modify this field. If ``update_mask`` is + omitted, this field is ignored and an existing enabled + setting cannot be disabled. + + This is a project-level setting and does not by itself + enable trace logging for any individual agent. Per-agent + trace logging is controlled by + ``DataAgent.bigquery_agent_analytics_enabled`` together with + ``DataAgent.bigquery_agent_analytics_table``; an agent does + not inherit this setting. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten by the update. The fields specified in the + update_mask are relative to the resource. A field will be + overwritten if it is in the mask. + + If the user does not provide a mask, only + ``telemetry_enabled`` will be updated (for backward + compatibility with legacy callers). Note that disabling + BigQuery Agent Analytics (``bqaa_enabled = false``) requires + providing an explicit ``update_mask`` containing + "bqaa_enabled". + + Per AIP-161: + + - The special wildcard value '\*' is supported to update all + fields. + - Field paths should use snake_case, though camelCase + equivalents (``telemetryEnabled``, ``bqaaEnabled``) are + accepted for REST/JSON transcoding compatibility. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + telemetry_enabled: bool = proto.Field( + proto.BOOL, + number=2, + ) + data_source_type: str = proto.Field( + proto.STRING, + number=3, + ) + bqaa_enabled: bool = proto.Field( + proto.BOOL, + number=4, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + + +class SetAgentOpsObservabilityResponse(proto.Message): + r"""Response for SetAgentOpsObservability.""" + + +class SetAgentOpsObservabilityMetadata(proto.Message): + r"""Metadata for SetAgentOpsObservability.""" + + +class RetrieveAgentOpsObservabilityRequest(proto.Message): + r"""Request for RetrieveAgentOpsObservability. + + Attributes: + parent (str): + Required. Parent value for + RetrieveAgentOpsObservabilityRequest. Format: + projects/{project}/locations/{location} + data_source_type (str): + Required. The data source type for which to + retrieve observability settings. Examples: + "bigquery", "looker". + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + data_source_type: str = proto.Field( + proto.STRING, + number=2, + ) + + +class RetrieveAgentOpsObservabilityResponse(proto.Message): + r"""Response for RetrieveAgentOpsObservability. + + Attributes: + telemetry_enabled (bool): + Output only. Whether AgentOps observability + telemetry is enabled. + bigquery_enabled (bool): + Output only. Whether BigQuery API is enabled. + cloud_trace_enabled (bool): + Output only. Whether Cloud Trace API is + enabled. + cloud_monitoring_enabled (bool): + Output only. Whether Cloud Monitoring API is + enabled. + cloud_logging_enabled (bool): + Output only. Whether Cloud Logging API is + enabled. + bqaa_enabled (bool): + Output only. Whether BigQuery Agent Analytics + is enabled. + """ + + telemetry_enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + bigquery_enabled: bool = proto.Field( + proto.BOOL, + number=3, + ) + cloud_trace_enabled: bool = proto.Field( + proto.BOOL, + number=4, + ) + cloud_monitoring_enabled: bool = proto.Field( + proto.BOOL, + number=5, + ) + cloud_logging_enabled: bool = proto.Field( + proto.BOOL, + number=6, + ) + bqaa_enabled: bool = proto.Field( + proto.BOOL, + number=7, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/data_chat_service.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/data_chat_service.py index e4e3bcaab6bb..aa5a6ff2506d 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/data_chat_service.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/data_chat_service.py @@ -25,7 +25,7 @@ from google.cloud.geminidataanalytics_v1alpha.types import ( credentials as gcg_credentials, ) -from google.cloud.geminidataanalytics_v1alpha.types import datasource +from google.cloud.geminidataanalytics_v1alpha.types import datasource, usage __protobuf__ = proto.module( package="google.cloud.geminidataanalytics.v1alpha", @@ -44,6 +44,7 @@ "ConversationReference", "ClientManagedResourceContext", "Message", + "LookerSettings", "UserMessage", "SystemMessage", "TextMessage", @@ -255,6 +256,8 @@ class QueryDataResponse(proto.Message): and may change at any time without notice. Do not write production code or business logic depending on the fields in this object. + token_usage (google.cloud.geminidataanalytics_v1alpha.types.TokenUsage): + Overall token usage for the request. """ generated_query: str = proto.Field( @@ -283,6 +286,11 @@ class QueryDataResponse(proto.Message): number=9, message=struct_pb2.Struct, ) + token_usage: usage.TokenUsage = proto.Field( + proto.MESSAGE, + number=10, + message=usage.TokenUsage, + ) class ExecutedQueryResult(proto.Message): @@ -297,13 +305,11 @@ class ExecutedQueryResult(proto.Message): total_row_count (int): The total number of rows in the full result set, if known. This may be an estimate or an - exact count. - - Note: if an internal limit (such as LIMIT 1000) - was applied during query execution to guard - against excessive data transfer, this count - reflects the truncated result size rather than - the unrestricted table result size. + exact count. Note: if an internal limit (such as + LIMIT 1000) was applied during query execution + to guard against excessive data transfer, this + count reflects the truncated result size rather + than the unrestricted table result size. partial_result (bool): Set to true if the returned rows in ``query_result`` are a subset of the full result. This can happen, for example, if @@ -523,17 +529,35 @@ class ChatRequest(proto.Message): conversations and agents resources. This field is a member of `oneof`_ ``context_provider``. + looker_settings (google.cloud.geminidataanalytics_v1alpha.types.LookerSettings): + Optional. Looker specific settings. + + This field is a member of `oneof`_ ``datasource_settings``. project (str): - Optional. The Google Cloud project to be used - for quota and billing. + Optional. Deprecated: Use ``parent`` field instead. The + Google Cloud project to be used for quota and billing. parent (str): Required. The parent value for chat request. Pattern: ``projects/{project}/locations/{location}`` messages (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.Message]): Required. Content of current conversation. + credentials (google.cloud.geminidataanalytics_v1alpha.types.Credentials): + Optional. The credentials to use when calling the data + source(s) specified in the context. + + This field can be used to provide credentials for various + data sources. For example, when connecting to Looker, it + currently supports both OAuth token and API key-based + credentials, as described in `Authentication with an + SDK `__. thinking_mode (google.cloud.geminidataanalytics_v1alpha.types.ChatRequest.ThinkingMode): Optional. The thinking mode to use for the agent loop. Defaults to THINKING_MODE_UNSPECIFIED if not specified. + model (google.cloud.geminidataanalytics_v1alpha.types.ChatRequest.Model): + Optional. The model to use for the agent loop + when processing the request. This setting only + has an effect when context.options.model is not + set. """ class ThinkingMode(proto.Enum): @@ -542,7 +566,8 @@ class ThinkingMode(proto.Enum): Values: THINKING_MODE_UNSPECIFIED (0): Unspecified thinking mode, agent will use - THINKING mode by default. + THINKING mode by default except for BigQuery + user defaulting to FAST mode by default. FAST (1): Fast mode, answers quickly. THINKING (2): @@ -553,6 +578,22 @@ class ThinkingMode(proto.Enum): FAST = 1 THINKING = 2 + class Model(proto.Enum): + r"""Model selection for the agent for BigQuery users. + + Values: + MODEL_UNSPECIFIED (0): + No model specified. Either preview or non + preview model can be used. + LATEST_GA_MODEL (1): + Use the most up-to-date non-preview model. + This may constrain certain request level + settings. + """ + + MODEL_UNSPECIFIED = 0 + LATEST_GA_MODEL = 1 + inline_context: gcg_context.Context = proto.Field( proto.MESSAGE, number=101, @@ -577,6 +618,12 @@ class ThinkingMode(proto.Enum): oneof="context_provider", message="ClientManagedResourceContext", ) + looker_settings: "LookerSettings" = proto.Field( + proto.MESSAGE, + number=13, + oneof="datasource_settings", + message="LookerSettings", + ) project: str = proto.Field( proto.STRING, number=1, @@ -590,11 +637,21 @@ class ThinkingMode(proto.Enum): number=2, message="Message", ) + credentials: gcg_credentials.Credentials = proto.Field( + proto.MESSAGE, + number=7, + message=gcg_credentials.Credentials, + ) thinking_mode: ThinkingMode = proto.Field( proto.ENUM, number=9, enum=ThinkingMode, ) + model: Model = proto.Field( + proto.ENUM, + number=11, + enum=Model, + ) class DataAgentContext(proto.Message): @@ -605,8 +662,8 @@ class DataAgentContext(proto.Message): Required. The name of the data agent resource. credentials (google.cloud.geminidataanalytics_v1alpha.types.Credentials): - Optional. The credentials to use when calling the Looker - data source. + Optional. Deprecated: Use credentials in ChatRequest. The + credentials to use when calling the Looker data source. Currently supports both OAuth token and API key-based credentials, as described in `Authentication with an @@ -763,6 +820,28 @@ class Message(proto.Message): ) +class LookerSettings(proto.Message): + r"""Message to hold Looker specific custom settings. + + Attributes: + enable_dev_mode (bool): + Optional. Whether to operate in Looker's + Development Mode. If true, the API session will + be switched to the "dev" workspace, allowing + interaction with LookML changes in the user's + development branch. If false or unset, the + session remains in the default state (Production + Mode). + See + https://cloud.google.com/looker/docs/dev-mode-prod-mode. + """ + + enable_dev_mode: bool = proto.Field( + proto.BOOL, + number=1, + ) + + class UserMessage(proto.Message): r"""A message from the user that is interacting with the system. @@ -785,7 +864,7 @@ class UserMessage(proto.Message): class SystemMessage(proto.Message): r"""A message from the system in response to the user. This message can also be a message from the user as historical - context for multiturn conversations with the system. + context for multi-turn conversations with the system. This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -826,8 +905,9 @@ class SystemMessage(proto.Message): This field is a member of `oneof`_ ``kind``. clarification (google.cloud.geminidataanalytics_v1alpha.types.ClarificationMessage): - Optional. A message containing clarification - questions. + Optional. Deprecated: Use TextMessage with + TextType.FINAL_RESPONSE instead. A message containing + clarification questions. This field is a member of `oneof`_ ``kind``. group_id (int): @@ -837,6 +917,9 @@ class SystemMessage(proto.Message): together in the UI. This field is a member of `oneof`_ ``_group_id``. + citation (google.cloud.geminidataanalytics_v1alpha.types.Citation): + Output only. Citation information for the + system message. """ text: "TextMessage" = proto.Field( @@ -892,6 +975,11 @@ class SystemMessage(proto.Message): number=12, optional=True, ) + citation: gcg_context.Citation = proto.Field( + proto.MESSAGE, + number=15, + message=gcg_context.Citation, + ) class TextMessage(proto.Message): @@ -924,12 +1012,17 @@ class TextType(proto.Enum): from the agent's internal thought process (``THOUGHT``) and the final answer to the user (``FINAL_RESPONSE``). These messages provide insight into the agent's actions. + FOLLOWUP_QUESTIONS (4): + The text is a list of follow-up questions + suggested. Each item in parts is a follow-up + question. """ TEXT_TYPE_UNSPECIFIED = 0 FINAL_RESPONSE = 1 THOUGHT = 2 PROGRESS = 3 + FOLLOWUP_QUESTIONS = 4 parts: MutableSequence[str] = proto.RepeatedField( proto.STRING, @@ -1037,15 +1130,20 @@ class DataMessage(proto.Message): This field is a member of `oneof`_ ``kind``. generated_looker_query (google.cloud.geminidataanalytics_v1alpha.types.LookerQuery): - Looker Query generated by the system to - retrieve data. Deprecated: generated looker - query is now under DataQuery.looker. + Deprecated: generated looker query is now + under DataQuery.looker. Looker Query generated + by the system to retrieve data. This field is a member of `oneof`_ ``kind``. big_query_job (google.cloud.geminidataanalytics_v1alpha.types.BigQueryJob): A BigQuery job executed by the system to retrieve data. + This field is a member of `oneof`_ ``kind``. + matched_query (google.cloud.geminidataanalytics_v1alpha.types.MatchedQuery): + A pre-existing query that was matched to + retrieve data. + This field is a member of `oneof`_ ``kind``. """ @@ -1078,6 +1176,12 @@ class DataMessage(proto.Message): oneof="kind", message="BigQueryJob", ) + matched_query: gcg_context.MatchedQuery = proto.Field( + proto.MESSAGE, + number=6, + oneof="kind", + message=gcg_context.MatchedQuery, + ) class DataQuery(proto.Message): @@ -1507,57 +1611,71 @@ class ErrorMessage(proto.Message): class ClarificationQuestion(proto.Message): - r"""Represents a single question to the user to help clarify - their query. + r"""Deprecated: Use TextMessage with TextType.FINAL_RESPONSE instead. + Represents a single question to the user to help clarify their + query. Attributes: question (str): - Required. The natural language question to - ask the user. + Required. Deprecated: The parent message is + deprecated. The natural language question to ask + the user. selection_mode (google.cloud.geminidataanalytics_v1alpha.types.ClarificationQuestion.SelectionMode): - Required. The selection mode for this + Required. Deprecated: The parent message is + deprecated. The selection mode for this question. options (MutableSequence[str]): - Required. A list of distinct options for the + Required. Deprecated: The parent message is + deprecated. A list of distinct options for the user to choose from. The number of options is limited to a maximum of 5. clarification_question_type (google.cloud.geminidataanalytics_v1alpha.types.ClarificationQuestion.ClarificationQuestionType): - Optional. The type of clarification question. + Optional. Deprecated: The parent message is + deprecated. The type of clarification question. """ class SelectionMode(proto.Enum): - r"""The selection mode for the clarification question. + r"""Deprecated: The parent message is deprecated. + The selection mode for the clarification question. Values: SELECTION_MODE_UNSPECIFIED (0): + Deprecated: The parent message is deprecated. Unspecified selection mode. SINGLE_SELECT (1): + Deprecated: The parent message is deprecated. The user can select only one option. MULTI_SELECT (2): + Deprecated: The parent message is deprecated. The user can select multiple options. """ + _pb_options = {"deprecated": True} SELECTION_MODE_UNSPECIFIED = 0 SINGLE_SELECT = 1 MULTI_SELECT = 2 class ClarificationQuestionType(proto.Enum): - r"""The type of clarification question. + r"""Deprecated: The parent message is deprecated. + The type of clarification question. This enum may be extended with new values in the future. Values: CLARIFICATION_QUESTION_TYPE_UNSPECIFIED (0): + Deprecated: The parent message is deprecated. Unspecified clarification question type. FILTER_VALUES (1): - The clarification question is for filter - values. + Deprecated: The parent message is deprecated. + The clarification question is for filter values. FIELDS (2): - The clarification question is for data - fields. This is a generic term encompassing SQL - columns, Looker fields (dimensions/measures), or - nested data structure properties. + Deprecated: The parent message is deprecated. + The clarification question is for data fields. + This is a generic term encompassing SQL columns, + Looker fields (dimensions/measures), or nested + data structure properties. """ + _pb_options = {"deprecated": True} CLARIFICATION_QUESTION_TYPE_UNSPECIFIED = 0 FILTER_VALUES = 1 FIELDS = 2 @@ -1583,13 +1701,15 @@ class ClarificationQuestionType(proto.Enum): class ClarificationMessage(proto.Message): - r"""A message of questions to help clarify the user's query. This - is returned when the system cannot confidently answer the user's + r"""Deprecated: Use TextMessage with TextType.FINAL_RESPONSE instead. A + message of questions to help clarify the user's query. This is + returned when the system cannot confidently answer the user's question. Attributes: questions (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.ClarificationQuestion]): - Required. A batch of clarification questions + Required. Deprecated: The parent message is + deprecated. A batch of clarification questions to ask the user. """ diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/datasource.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/datasource.py index 7b0a35c48594..9fe5045e8dd4 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/datasource.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/datasource.py @@ -47,6 +47,7 @@ "CloudSqlDatabaseReference", "LookerExploreReferences", "LookerExploreReference", + "BigQueryPropertyGraphReference", "PrivateLookerInstanceInfo", "Datasource", "Schema", @@ -173,12 +174,20 @@ class DatasourceReferences(proto.Message): class BigQueryTableReferences(proto.Message): r"""Message representing references to BigQuery tables and property - graphs. At least one of ``table_references`` or - ``property_graph_references`` must be populated. + graphs. At least one of ``table_references``, + ``property_graph_references``, or ``search_scope`` must be + populated. Attributes: table_references (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.BigQueryTableReference]): Optional. References to BigQuery tables. + property_graph_references (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.BigQueryPropertyGraphReference]): + Optional. References to BigQuery graphs. + + Note: "property graph" is the former name for + BigQuery Graph. The field and message names + retain the original term for backward + compatibility; both refer to the same resource. agent_context_reference (google.cloud.geminidataanalytics_v1alpha.types.AgentContextReference): Optional. Parameters for retrieving data from Agent Context. @@ -189,6 +198,13 @@ class BigQueryTableReferences(proto.Message): number=1, message="BigQueryTableReference", ) + property_graph_references: MutableSequence["BigQueryPropertyGraphReference"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=2, + message="BigQueryPropertyGraphReference", + ) + ) agent_context_reference: agent_context.AgentContextReference = proto.Field( proto.MESSAGE, number=4, @@ -236,7 +252,8 @@ class StudioDatasourceReferences(proto.Message): Attributes: studio_references (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.StudioDatasourceReference]): - The references to the studio datasources. + Optional. The references to the studio + datasources. """ studio_references: MutableSequence["StudioDatasourceReference"] = ( @@ -754,8 +771,8 @@ class LookerExploreReferences(proto.Message): explore_references (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.LookerExploreReference]): Required. References to Looker explores. credentials (google.cloud.geminidataanalytics_v1alpha.types.Credentials): - Optional. The credentials to use when calling the Looker - API. + Optional. Deprecated: Use credentials in ChatRequest. The + credentials to use when calling the Looker API. Currently supports both OAuth token and API key-based credentials, as described in `Authentication with an @@ -832,6 +849,35 @@ class LookerExploreReference(proto.Message): ) +class BigQueryPropertyGraphReference(proto.Message): + r"""Message representing a reference to a single BigQuery + property graph. + + Attributes: + project_id (str): + Required. The project that the property graph + belongs to. + dataset_id (str): + Required. The dataset that the property graph + belongs to. + property_graph_id (str): + Required. The property graph id. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + dataset_id: str = proto.Field( + proto.STRING, + number=2, + ) + property_graph_id: str = proto.Field( + proto.STRING, + number=3, + ) + + class PrivateLookerInstanceInfo(proto.Message): r"""Message representing a private Looker instance info required if the Looker instance is behind a private network. @@ -892,6 +938,10 @@ class Datasource(proto.Message): bigtable_reference (google.cloud.geminidataanalytics_v1alpha.types.BigtableReference): A reference to a Bigtable instance. + This field is a member of `oneof`_ ``reference``. + bigquery_property_graph_reference (google.cloud.geminidataanalytics_v1alpha.types.BigQueryPropertyGraphReference): + A reference to a BigQuery property graph. + This field is a member of `oneof`_ ``reference``. firestore_reference (google.cloud.geminidataanalytics_v1alpha.types.FirestoreReference): A reference to a Firestore database. @@ -950,6 +1000,12 @@ class Datasource(proto.Message): oneof="reference", message="BigtableReference", ) + bigquery_property_graph_reference: "BigQueryPropertyGraphReference" = proto.Field( + proto.MESSAGE, + number=16, + oneof="reference", + message="BigQueryPropertyGraphReference", + ) firestore_reference: "FirestoreReference" = proto.Field( proto.MESSAGE, number=17, @@ -1058,9 +1114,7 @@ class Field(proto.Message): schema structures. category (str): Optional. Field category, not required, - currently only useful for Looker. We are using a - string to avoid depending on an external package - and keep this package self-contained. + currently only useful for Looker. value_format (str): Optional. Looker only. Value format of the field. Ref: diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/usage.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/usage.py new file mode 100644 index 000000000000..666d4da389dd --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/usage.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.geminidataanalytics.v1alpha", + manifest={ + "TokenUsage", + }, +) + + +class TokenUsage(proto.Message): + r"""Overall token usage tracking for the response. + + Attributes: + input_token_count (int): + The total number of input tokens used in this + request. + output_token_count (int): + The total number of output tokens used in + this request. + """ + + input_token_count: int = proto.Field( + proto.INT32, + number=1, + ) + output_token_count: int = proto.Field( + proto.INT32, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/__init__.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/__init__.py index f8fa69e86cb7..e34af27fa52e 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/__init__.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/__init__.py @@ -26,20 +26,24 @@ # https://docs.python.org/3.15/library/sys.html#sys.set_lazy_imports_filter # Older Python versions safely ignore this variable. __lazy_modules__ = { + "google.cloud.geminidataanalytics_v1beta.services.data_a2a_service", "google.cloud.geminidataanalytics_v1beta.services.data_agent_service", "google.cloud.geminidataanalytics_v1beta.services.data_chat_service", "google.cloud.geminidataanalytics_v1beta.types.agent_context", "google.cloud.geminidataanalytics_v1beta.types.context", "google.cloud.geminidataanalytics_v1beta.types.conversation", "google.cloud.geminidataanalytics_v1beta.types.credentials", + "google.cloud.geminidataanalytics_v1beta.types.data_a2a_service", "google.cloud.geminidataanalytics_v1beta.types.data_agent", "google.cloud.geminidataanalytics_v1beta.types.data_agent_service", "google.cloud.geminidataanalytics_v1beta.types.data_analytics_agent", "google.cloud.geminidataanalytics_v1beta.types.data_chat_service", "google.cloud.geminidataanalytics_v1beta.types.datasource", + "google.cloud.geminidataanalytics_v1beta.types.usage", } +from .services.data_a2a_service import DataA2AServiceAsyncClient, DataA2AServiceClient from .services.data_agent_service import ( DataAgentServiceAsyncClient, DataAgentServiceClient, @@ -60,6 +64,7 @@ Context, ConversationOptions, DatasourceOptions, + DynamicField, ExampleQuery, GlossaryTerm, LookerGoldenQuery, @@ -76,8 +81,49 @@ GetConversationRequest, ListConversationsRequest, ListConversationsResponse, + UpdateConversationRequest, ) from .types.credentials import Credentials, OAuthCredentials +from .types.data_a2a_service import ( + A2AArtifact, + A2AMessage, + A2ATask, + AgentCapabilities, + AgentCard, + AgentCardSignature, + AgentExtension, + AgentInterface, + AgentProvider, + AgentSkill, + APIKeySecurityScheme, + AuthenticationInfo, + AuthorizationCodeOAuthFlow, + ClientCredentialsOAuthFlow, + DataPart, + FilePart, + GetAgentCardRequest, + HTTPAuthSecurityScheme, + ImplicitOAuthFlow, + MutualTlsSecurityScheme, + OAuth2SecurityScheme, + OAuthFlows, + OpenIdConnectSecurityScheme, + Part, + PasswordOAuthFlow, + PushNotificationConfig, + Role, + Security, + SecurityScheme, + SendMessageConfiguration, + SendMessageRequest, + SendMessageResponse, + StreamResponse, + StringList, + TaskArtifactUpdateEvent, + TaskState, + TaskStatus, + TaskStatusUpdateEvent, +) from .types.data_agent import DataAgent from .types.data_agent_service import ( CreateDataAgentRequest, @@ -88,6 +134,11 @@ ListDataAgentsRequest, ListDataAgentsResponse, OperationMetadata, + RetrieveAgentOpsObservabilityRequest, + RetrieveAgentOpsObservabilityResponse, + SetAgentOpsObservabilityMetadata, + SetAgentOpsObservabilityRequest, + SetAgentOpsObservabilityResponse, UpdateDataAgentRequest, ) from .types.data_analytics_agent import DataAnalyticsAgent @@ -156,17 +207,32 @@ StudioDatasourceReference, StudioDatasourceReferences, ) +from .types.usage import TokenUsage __all__ = ( + "DataA2AServiceAsyncClient", "DataAgentServiceAsyncClient", "DataChatServiceAsyncClient", + "A2AArtifact", + "A2AMessage", + "A2ATask", + "APIKeySecurityScheme", + "AgentCapabilities", + "AgentCard", + "AgentCardSignature", "AgentContextReference", + "AgentExtension", + "AgentInterface", + "AgentProvider", + "AgentSkill", "AlloyDbDatabaseReference", "AlloyDbReference", "AnalysisEvent", "AnalysisMessage", "AnalysisOptions", "AnalysisQuery", + "AuthenticationInfo", + "AuthorizationCodeOAuthFlow", "BigQueryJob", "BigQueryPropertyGraphReference", "BigQueryRoutine", @@ -186,6 +252,7 @@ "CitationSource", "ClarificationMessage", "ClarificationQuestion", + "ClientCredentialsOAuthFlow", "ClientManagedResourceContext", "CloudSqlDatabaseReference", "CloudSqlReference", @@ -196,6 +263,7 @@ "CreateConversationRequest", "CreateDataAgentRequest", "Credentials", + "DataA2AServiceClient", "DataAgent", "DataAgentContext", "DataAgentServiceClient", @@ -204,6 +272,7 @@ "DataFilter", "DataFilterType", "DataMessage", + "DataPart", "DataQuery", "DataResult", "DatabaseTableReference", @@ -212,17 +281,22 @@ "DatasourceReferences", "DeleteConversationRequest", "DeleteDataAgentRequest", + "DynamicField", "ErrorMessage", "ExampleQueries", "ExampleQuery", "ExecutedQueryResult", "Field", + "FilePart", "FirestoreDatabaseReference", "FirestoreReference", "GenerationOptions", + "GetAgentCardRequest", "GetConversationRequest", "GetDataAgentRequest", "GlossaryTerm", + "HTTPAuthSecurityScheme", + "ImplicitOAuthFlow", "ListAccessibleDataAgentsRequest", "ListAccessibleDataAgentsResponse", "ListConversationsRequest", @@ -238,26 +312,52 @@ "LookerSettings", "MatchedQuery", "Message", + "MutualTlsSecurityScheme", + "OAuth2SecurityScheme", "OAuthCredentials", + "OAuthFlows", + "OpenIdConnectSecurityScheme", "OperationMetadata", "ParameterizedSecureViewParameters", + "Part", + "PasswordOAuthFlow", "PrivateLookerInstanceInfo", + "PushNotificationConfig", "QueryDataContext", "QueryDataRequest", "QueryDataResponse", "QueryParameter", "QueryParameterValues", + "RetrieveAgentOpsObservabilityRequest", + "RetrieveAgentOpsObservabilityResponse", + "Role", "Schema", "SchemaMessage", "SchemaQuery", "SchemaResult", + "Security", + "SecurityScheme", + "SendMessageConfiguration", + "SendMessageRequest", + "SendMessageResponse", + "SetAgentOpsObservabilityMetadata", + "SetAgentOpsObservabilityRequest", + "SetAgentOpsObservabilityResponse", "SpannerDatabaseReference", "SpannerReference", "StorageMessage", + "StreamResponse", + "StringList", "StudioDatasourceReference", "StudioDatasourceReferences", "SystemMessage", + "TaskArtifactUpdateEvent", + "TaskState", + "TaskStatus", + "TaskStatusUpdateEvent", "TextMessage", + "TokenUsage", + "UpdateConversationRequest", "UpdateDataAgentRequest", "UserFunctions", "UserMessage", diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/gapic_metadata.json b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/gapic_metadata.json index 00fa81d0a123..5af8900a1ecc 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/gapic_metadata.json +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/gapic_metadata.json @@ -5,6 +5,70 @@ "protoPackage": "google.cloud.geminidataanalytics.v1beta", "schema": "1.0", "services": { + "DataA2AService": { + "clients": { + "grpc": { + "libraryClient": "DataA2AServiceClient", + "rpcs": { + "GetAgentCard": { + "methods": [ + "get_agent_card" + ] + }, + "SendMessage": { + "methods": [ + "send_message" + ] + }, + "SendStreamingMessage": { + "methods": [ + "send_streaming_message" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DataA2AServiceAsyncClient", + "rpcs": { + "GetAgentCard": { + "methods": [ + "get_agent_card" + ] + }, + "SendMessage": { + "methods": [ + "send_message" + ] + }, + "SendStreamingMessage": { + "methods": [ + "send_streaming_message" + ] + } + } + }, + "rest": { + "libraryClient": "DataA2AServiceClient", + "rpcs": { + "GetAgentCard": { + "methods": [ + "get_agent_card" + ] + }, + "SendMessage": { + "methods": [ + "send_message" + ] + }, + "SendStreamingMessage": { + "methods": [ + "send_streaming_message" + ] + } + } + } + } + }, "DataAgentService": { "clients": { "grpc": { @@ -50,6 +114,16 @@ "list_data_agents" ] }, + "RetrieveAgentOpsObservability": { + "methods": [ + "retrieve_agent_ops_observability" + ] + }, + "SetAgentOpsObservability": { + "methods": [ + "set_agent_ops_observability" + ] + }, "SetIamPolicy": { "methods": [ "set_iam_policy" @@ -110,6 +184,16 @@ "list_data_agents" ] }, + "RetrieveAgentOpsObservability": { + "methods": [ + "retrieve_agent_ops_observability" + ] + }, + "SetAgentOpsObservability": { + "methods": [ + "set_agent_ops_observability" + ] + }, "SetIamPolicy": { "methods": [ "set_iam_policy" @@ -170,6 +254,16 @@ "list_data_agents" ] }, + "RetrieveAgentOpsObservability": { + "methods": [ + "retrieve_agent_ops_observability" + ] + }, + "SetAgentOpsObservability": { + "methods": [ + "set_agent_ops_observability" + ] + }, "SetIamPolicy": { "methods": [ "set_iam_policy" @@ -228,6 +322,11 @@ "methods": [ "query_data" ] + }, + "UpdateConversation": { + "methods": [ + "update_conversation" + ] } } }, @@ -268,6 +367,11 @@ "methods": [ "query_data" ] + }, + "UpdateConversation": { + "methods": [ + "update_conversation" + ] } } }, @@ -308,6 +412,11 @@ "methods": [ "query_data" ] + }, + "UpdateConversation": { + "methods": [ + "update_conversation" + ] } } } diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/__init__.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/__init__.py new file mode 100644 index 000000000000..5c4c8745b6ac --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import DataA2AServiceAsyncClient +from .client import DataA2AServiceClient + +__all__ = ( + "DataA2AServiceClient", + "DataA2AServiceAsyncClient", +) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/async_client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/async_client.py new file mode 100644 index 000000000000..6d589404c571 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/async_client.py @@ -0,0 +1,1017 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + AsyncIterable, + Awaitable, + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.geminidataanalytics_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.geminidataanalytics_v1beta.types import data_a2a_service + +from .client import DataA2AServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, DataA2AServiceTransport +from .transports.grpc_asyncio import DataA2AServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class DataA2AServiceAsyncClient: + """DataA2AService defines the Agent-to-Agent (A2A) protocol + service for Gemini Data Analytics. + """ + + _client: DataA2AServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = DataA2AServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DataA2AServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = DataA2AServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = DataA2AServiceClient._DEFAULT_UNIVERSE + + common_billing_account_path = staticmethod( + DataA2AServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + DataA2AServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(DataA2AServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + DataA2AServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + DataA2AServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + DataA2AServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(DataA2AServiceClient.common_project_path) + parse_common_project_path = staticmethod( + DataA2AServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(DataA2AServiceClient.common_location_path) + parse_common_location_path = staticmethod( + DataA2AServiceClient.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: + DataA2AServiceAsyncClient: The constructed client. + """ + sa_info_func = ( + DataA2AServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(DataA2AServiceAsyncClient, info, *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: + DataA2AServiceAsyncClient: The constructed client. + """ + sa_file_func = ( + DataA2AServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(DataA2AServiceAsyncClient, filename, *args, **kwargs) + + 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 DataA2AServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DataA2AServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DataA2AServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = DataA2AServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, DataA2AServiceTransport, Callable[..., DataA2AServiceTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the data a2a service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,DataA2AServiceTransport,Callable[..., DataA2AServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the DataA2AServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = DataA2AServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.geminidataanalytics_v1beta.DataA2AServiceAsyncClient`.", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "credentialsType": None, + }, + ) + + async def send_message( + self, + request: Optional[Union[data_a2a_service.SendMessageRequest, dict]] = None, + *, + tenant: Optional[str] = None, + message: Optional[data_a2a_service.A2AMessage] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_a2a_service.SendMessageResponse: + r"""Send a message to the agent. This is a blocking call + that will return the task once it is completed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1beta + + async def sample_send_message(): + # Create a client + client = geminidataanalytics_v1beta.DataA2AServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.SendMessageRequest( + ) + + # Make the request + response = await client.send_message(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.geminidataanalytics_v1beta.types.SendMessageRequest, dict]]): + The request object. Request message for SendMessage and + SendStreamingMessage. + tenant (:class:`str`): + Optional. Optional tenant, provided + as a path parameter. + + This corresponds to the ``tenant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message (:class:`google.cloud.geminidataanalytics_v1beta.types.A2AMessage`): + Required. The message to send to the + agent. + + This corresponds to the ``message`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1beta.types.SendMessageResponse: + Response message for SendMessage. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [tenant, message] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, data_a2a_service.SendMessageRequest): + request = data_a2a_service.SendMessageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tenant is not None: + request.tenant = tenant + if message is not None: + request.message = message + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.send_message + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("tenant", request.tenant),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def send_streaming_message( + self, + request: Optional[Union[data_a2a_service.SendMessageRequest, dict]] = None, + *, + tenant: Optional[str] = None, + message: Optional[data_a2a_service.A2AMessage] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Awaitable[AsyncIterable[data_a2a_service.StreamResponse]]: + r"""SendStreamingMessage is a streaming call that will + return a stream of task update events until the Task is + in an interrupted or terminal state. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1beta + + async def sample_send_streaming_message(): + # Create a client + client = geminidataanalytics_v1beta.DataA2AServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.SendMessageRequest( + ) + + # Make the request + stream = await client.send_streaming_message(request=request) + + # Handle the response + async for response in stream: + print(response) + + Args: + request (Optional[Union[google.cloud.geminidataanalytics_v1beta.types.SendMessageRequest, dict]]): + The request object. Request message for SendMessage and + SendStreamingMessage. + tenant (:class:`str`): + Optional. Optional tenant, provided + as a path parameter. + + This corresponds to the ``tenant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message (:class:`google.cloud.geminidataanalytics_v1beta.types.A2AMessage`): + Required. The message to send to the + agent. + + This corresponds to the ``message`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + AsyncIterable[google.cloud.geminidataanalytics_v1beta.types.StreamResponse]: + The stream response for a message. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [tenant, message] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, data_a2a_service.SendMessageRequest): + request = data_a2a_service.SendMessageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tenant is not None: + request.tenant = tenant + if message is not None: + request.message = message + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.send_streaming_message + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("tenant", request.tenant),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_agent_card( + self, + request: Optional[Union[data_a2a_service.GetAgentCardRequest, dict]] = None, + *, + tenant: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_a2a_service.AgentCard: + r"""GetAgentCard returns the agent card for the agent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1beta + + async def sample_get_agent_card(): + # Create a client + client = geminidataanalytics_v1beta.DataA2AServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.GetAgentCardRequest( + ) + + # Make the request + response = await client.get_agent_card(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.geminidataanalytics_v1beta.types.GetAgentCardRequest, dict]]): + The request object. Request message for GetAgentCard. + tenant (:class:`str`): + Optional. Optional tenant, provided + as a path parameter. + + This corresponds to the ``tenant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1beta.types.AgentCard: + AgentCard conveys key information + about an agent. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [tenant] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, data_a2a_service.GetAgentCardRequest): + request = data_a2a_service.GetAgentCardRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tenant is not None: + request.tenant = tenant + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_agent_card + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("tenant", request.tenant),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "DataA2AServiceAsyncClient": + 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__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("DataA2AServiceAsyncClient",) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/client.py new file mode 100644 index 000000000000..198c033931a3 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/client.py @@ -0,0 +1,1306 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Iterable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +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.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.geminidataanalytics_v1beta import gapic_version as package_version +from google.cloud.geminidataanalytics_v1beta._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.geminidataanalytics_v1beta.types import data_a2a_service + +from .transports.base import DEFAULT_CLIENT_INFO, DataA2AServiceTransport +from .transports.grpc import DataA2AServiceGrpcTransport +from .transports.grpc_asyncio import DataA2AServiceGrpcAsyncIOTransport +from .transports.rest import DataA2AServiceRestTransport + + +class DataA2AServiceClientMeta(type): + """Metaclass for the DataA2AService 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[DataA2AServiceTransport]] + _transport_registry["grpc"] = DataA2AServiceGrpcTransport + _transport_registry["grpc_asyncio"] = DataA2AServiceGrpcAsyncIOTransport + _transport_registry["rest"] = DataA2AServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[DataA2AServiceTransport]: + """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 DataA2AServiceClient(metaclass=DataA2AServiceClientMeta): + """DataA2AService defines the Agent-to-Agent (A2A) protocol + service for Gemini Data Analytics. + """ + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "geminidataanalytics.googleapis.com" + DEFAULT_MTLS_ENDPOINT = get_default_mtls_endpoint(DEFAULT_ENDPOINT) + + _DEFAULT_ENDPOINT_TEMPLATE = "geminidataanalytics.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DataA2AServiceClient: 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: + DataA2AServiceClient: 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) -> DataA2AServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DataA2AServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = should_use_client_cert() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + 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: + 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 # type: ignore + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, DataA2AServiceTransport, Callable[..., DataA2AServiceTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the data a2a service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,DataA2AServiceTransport,Callable[..., DataA2AServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the DataA2AServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = DataA2AServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=DataA2AServiceClient._DEFAULT_UNIVERSE, + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, DataA2AServiceTransport) + if transport_provided: + # transport is a DataA2AServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(DataA2AServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=DataA2AServiceClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=DataA2AServiceClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=DataA2AServiceClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[DataA2AServiceTransport], Callable[..., DataA2AServiceTransport] + ] = ( + DataA2AServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., DataA2AServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.geminidataanalytics_v1beta.DataA2AServiceClient`.", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "credentialsType": None, + }, + ) + + def send_message( + self, + request: Optional[Union[data_a2a_service.SendMessageRequest, dict]] = None, + *, + tenant: Optional[str] = None, + message: Optional[data_a2a_service.A2AMessage] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_a2a_service.SendMessageResponse: + r"""Send a message to the agent. This is a blocking call + that will return the task once it is completed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1beta + + def sample_send_message(): + # Create a client + client = geminidataanalytics_v1beta.DataA2AServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.SendMessageRequest( + ) + + # Make the request + response = client.send_message(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.geminidataanalytics_v1beta.types.SendMessageRequest, dict]): + The request object. Request message for SendMessage and + SendStreamingMessage. + tenant (str): + Optional. Optional tenant, provided + as a path parameter. + + This corresponds to the ``tenant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message (google.cloud.geminidataanalytics_v1beta.types.A2AMessage): + Required. The message to send to the + agent. + + This corresponds to the ``message`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1beta.types.SendMessageResponse: + Response message for SendMessage. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [tenant, message] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, data_a2a_service.SendMessageRequest): + request = data_a2a_service.SendMessageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tenant is not None: + request.tenant = tenant + if message is not None: + request.message = message + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.send_message] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("tenant", request.tenant),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def send_streaming_message( + self, + request: Optional[Union[data_a2a_service.SendMessageRequest, dict]] = None, + *, + tenant: Optional[str] = None, + message: Optional[data_a2a_service.A2AMessage] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[data_a2a_service.StreamResponse]: + r"""SendStreamingMessage is a streaming call that will + return a stream of task update events until the Task is + in an interrupted or terminal state. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1beta + + def sample_send_streaming_message(): + # Create a client + client = geminidataanalytics_v1beta.DataA2AServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.SendMessageRequest( + ) + + # Make the request + stream = client.send_streaming_message(request=request) + + # Handle the response + for response in stream: + print(response) + + Args: + request (Union[google.cloud.geminidataanalytics_v1beta.types.SendMessageRequest, dict]): + The request object. Request message for SendMessage and + SendStreamingMessage. + tenant (str): + Optional. Optional tenant, provided + as a path parameter. + + This corresponds to the ``tenant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message (google.cloud.geminidataanalytics_v1beta.types.A2AMessage): + Required. The message to send to the + agent. + + This corresponds to the ``message`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + Iterable[google.cloud.geminidataanalytics_v1beta.types.StreamResponse]: + The stream response for a message. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [tenant, message] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, data_a2a_service.SendMessageRequest): + request = data_a2a_service.SendMessageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tenant is not None: + request.tenant = tenant + if message is not None: + request.message = message + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.send_streaming_message] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("tenant", request.tenant),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_agent_card( + self, + request: Optional[Union[data_a2a_service.GetAgentCardRequest, dict]] = None, + *, + tenant: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_a2a_service.AgentCard: + r"""GetAgentCard returns the agent card for the agent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1beta + + def sample_get_agent_card(): + # Create a client + client = geminidataanalytics_v1beta.DataA2AServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.GetAgentCardRequest( + ) + + # Make the request + response = client.get_agent_card(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.geminidataanalytics_v1beta.types.GetAgentCardRequest, dict]): + The request object. Request message for GetAgentCard. + tenant (str): + Optional. Optional tenant, provided + as a path parameter. + + This corresponds to the ``tenant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1beta.types.AgentCard: + AgentCard conveys key information + about an agent. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [tenant] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, data_a2a_service.GetAgentCardRequest): + request = data_a2a_service.GetAgentCardRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tenant is not None: + request.tenant = tenant + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_agent_card] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("tenant", request.tenant),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "DataA2AServiceClient": + 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[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("DataA2AServiceClient",) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/README.rst b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/README.rst new file mode 100644 index 000000000000..991eb507e49d --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``DataA2AServiceTransport`` is the ABC for all transports. + +- public child ``DataA2AServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``DataA2AServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseDataA2AServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``DataA2AServiceRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/__init__.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/__init__.py new file mode 100644 index 000000000000..d9bac7b888fc --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 DataA2AServiceTransport +from .grpc import DataA2AServiceGrpcTransport +from .grpc_asyncio import DataA2AServiceGrpcAsyncIOTransport +from .rest import DataA2AServiceRestInterceptor, DataA2AServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DataA2AServiceTransport]] +_transport_registry["grpc"] = DataA2AServiceGrpcTransport +_transport_registry["grpc_asyncio"] = DataA2AServiceGrpcAsyncIOTransport +_transport_registry["rest"] = DataA2AServiceRestTransport + +__all__ = ( + "DataA2AServiceTransport", + "DataA2AServiceGrpcTransport", + "DataA2AServiceGrpcAsyncIOTransport", + "DataA2AServiceRestTransport", + "DataA2AServiceRestInterceptor", +) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/base.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/base.py new file mode 100644 index 000000000000..6089c207e0e3 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/base.py @@ -0,0 +1,298 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +import google.api_core +import google.auth # type: ignore +import google.protobuf +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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.geminidataanalytics_v1beta import gapic_version as package_version +from google.cloud.geminidataanalytics_v1beta.types import data_a2a_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class DataA2AServiceTransport(abc.ABC): + """Abstract transport class for DataA2AService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "geminidataanalytics.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'geminidataanalytics.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.send_message: gapic_v1.method.wrap_method( + self.send_message, + default_timeout=None, + client_info=client_info, + ), + self.send_streaming_message: gapic_v1.method.wrap_method( + self.send_streaming_message, + default_timeout=None, + client_info=client_info, + ), + self.get_agent_card: gapic_v1.method.wrap_method( + self.get_agent_card, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def send_message( + self, + ) -> Callable[ + [data_a2a_service.SendMessageRequest], + Union[ + data_a2a_service.SendMessageResponse, + Awaitable[data_a2a_service.SendMessageResponse], + ], + ]: + raise NotImplementedError() + + @property + def send_streaming_message( + self, + ) -> Callable[ + [data_a2a_service.SendMessageRequest], + Union[ + data_a2a_service.StreamResponse, Awaitable[data_a2a_service.StreamResponse] + ], + ]: + raise NotImplementedError() + + @property + def get_agent_card( + self, + ) -> Callable[ + [data_a2a_service.GetAgentCardRequest], + Union[data_a2a_service.AgentCard, Awaitable[data_a2a_service.AgentCard]], + ]: + 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 get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("DataA2AServiceTransport",) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/grpc.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/grpc.py new file mode 100644 index 000000000000..8cc65f8e8809 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/grpc.py @@ -0,0 +1,530 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.geminidataanalytics_v1beta.types import data_a2a_service + +from .base import DEFAULT_CLIENT_INFO, DataA2AServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class DataA2AServiceGrpcTransport(DataA2AServiceTransport): + """gRPC backend transport for DataA2AService. + + DataA2AService defines the Agent-to-Agent (A2A) protocol + service for Gemini Data Analytics. + + 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 = "geminidataanalytics.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'geminidataanalytics.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "geminidataanalytics.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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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 send_message( + self, + ) -> Callable[ + [data_a2a_service.SendMessageRequest], data_a2a_service.SendMessageResponse + ]: + r"""Return a callable for the send message method over gRPC. + + Send a message to the agent. This is a blocking call + that will return the task once it is completed. + + Returns: + Callable[[~.SendMessageRequest], + ~.SendMessageResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "send_message" not in self._stubs: + self._stubs["send_message"] = self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1beta.DataA2AService/SendMessage", + request_serializer=data_a2a_service.SendMessageRequest.serialize, + response_deserializer=data_a2a_service.SendMessageResponse.deserialize, + ) + return self._stubs["send_message"] + + @property + def send_streaming_message( + self, + ) -> Callable[ + [data_a2a_service.SendMessageRequest], data_a2a_service.StreamResponse + ]: + r"""Return a callable for the send streaming message method over gRPC. + + SendStreamingMessage is a streaming call that will + return a stream of task update events until the Task is + in an interrupted or terminal state. + + Returns: + Callable[[~.SendMessageRequest], + ~.StreamResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "send_streaming_message" not in self._stubs: + self._stubs["send_streaming_message"] = self._logged_channel.unary_stream( + "/google.cloud.geminidataanalytics.v1beta.DataA2AService/SendStreamingMessage", + request_serializer=data_a2a_service.SendMessageRequest.serialize, + response_deserializer=data_a2a_service.StreamResponse.deserialize, + ) + return self._stubs["send_streaming_message"] + + @property + def get_agent_card( + self, + ) -> Callable[[data_a2a_service.GetAgentCardRequest], data_a2a_service.AgentCard]: + r"""Return a callable for the get agent card method over gRPC. + + GetAgentCard returns the agent card for the agent. + + Returns: + Callable[[~.GetAgentCardRequest], + ~.AgentCard]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent_card" not in self._stubs: + self._stubs["get_agent_card"] = self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1beta.DataA2AService/GetAgentCard", + request_serializer=data_a2a_service.GetAgentCardRequest.serialize, + response_deserializer=data_a2a_service.AgentCard.deserialize, + ) + return self._stubs["get_agent_card"] + + def close(self): + self._logged_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._logged_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._logged_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._logged_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._logged_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 list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("DataA2AServiceGrpcTransport",) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/grpc_asyncio.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..e3e534bd3b64 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/grpc_asyncio.py @@ -0,0 +1,597 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.geminidataanalytics_v1beta.types import data_a2a_service + +from .base import DEFAULT_CLIENT_INFO, DataA2AServiceTransport +from .grpc import DataA2AServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class DataA2AServiceGrpcAsyncIOTransport(DataA2AServiceTransport): + """gRPC AsyncIO backend transport for DataA2AService. + + DataA2AService defines the Agent-to-Agent (A2A) protocol + service for Gemini Data Analytics. + + 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 = "geminidataanalytics.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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + 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 = "geminidataanalytics.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'geminidataanalytics.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_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 send_message( + self, + ) -> Callable[ + [data_a2a_service.SendMessageRequest], + Awaitable[data_a2a_service.SendMessageResponse], + ]: + r"""Return a callable for the send message method over gRPC. + + Send a message to the agent. This is a blocking call + that will return the task once it is completed. + + Returns: + Callable[[~.SendMessageRequest], + Awaitable[~.SendMessageResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "send_message" not in self._stubs: + self._stubs["send_message"] = self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1beta.DataA2AService/SendMessage", + request_serializer=data_a2a_service.SendMessageRequest.serialize, + response_deserializer=data_a2a_service.SendMessageResponse.deserialize, + ) + return self._stubs["send_message"] + + @property + def send_streaming_message( + self, + ) -> Callable[ + [data_a2a_service.SendMessageRequest], + Awaitable[data_a2a_service.StreamResponse], + ]: + r"""Return a callable for the send streaming message method over gRPC. + + SendStreamingMessage is a streaming call that will + return a stream of task update events until the Task is + in an interrupted or terminal state. + + Returns: + Callable[[~.SendMessageRequest], + Awaitable[~.StreamResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "send_streaming_message" not in self._stubs: + self._stubs["send_streaming_message"] = self._logged_channel.unary_stream( + "/google.cloud.geminidataanalytics.v1beta.DataA2AService/SendStreamingMessage", + request_serializer=data_a2a_service.SendMessageRequest.serialize, + response_deserializer=data_a2a_service.StreamResponse.deserialize, + ) + return self._stubs["send_streaming_message"] + + @property + def get_agent_card( + self, + ) -> Callable[ + [data_a2a_service.GetAgentCardRequest], Awaitable[data_a2a_service.AgentCard] + ]: + r"""Return a callable for the get agent card method over gRPC. + + GetAgentCard returns the agent card for the agent. + + Returns: + Callable[[~.GetAgentCardRequest], + Awaitable[~.AgentCard]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent_card" not in self._stubs: + self._stubs["get_agent_card"] = self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1beta.DataA2AService/GetAgentCard", + request_serializer=data_a2a_service.GetAgentCardRequest.serialize, + response_deserializer=data_a2a_service.AgentCard.deserialize, + ) + return self._stubs["get_agent_card"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.send_message: self._wrap_method( + self.send_message, + default_timeout=None, + client_info=client_info, + ), + self.send_streaming_message: self._wrap_method( + self.send_streaming_message, + default_timeout=None, + client_info=client_info, + ), + self.get_agent_card: self._wrap_method( + self.get_agent_card, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @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._logged_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._logged_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._logged_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._logged_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 list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ("DataA2AServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/rest.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/rest.py new file mode 100644 index 000000000000..90070a03cfa9 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/rest.py @@ -0,0 +1,1765 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.geminidataanalytics_v1beta._compat import transcode_request +from google.cloud.geminidataanalytics_v1beta.types import data_a2a_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseDataA2AServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class DataA2AServiceRestInterceptor: + """Interceptor for DataA2AService. + + 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 DataA2AServiceRestTransport. + + .. code-block:: python + class MyCustomDataA2AServiceInterceptor(DataA2AServiceRestInterceptor): + def pre_get_agent_card(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_agent_card(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_send_message(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_send_message(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_send_streaming_message(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_send_streaming_message(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DataA2AServiceRestTransport(interceptor=MyCustomDataA2AServiceInterceptor()) + client = DataA2AServiceClient(transport=transport) + + + """ + + def pre_get_agent_card( + self, + request: data_a2a_service.GetAgentCardRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_a2a_service.GetAgentCardRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_agent_card + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataA2AService server. + """ + return request, metadata + + def post_get_agent_card( + self, response: data_a2a_service.AgentCard + ) -> data_a2a_service.AgentCard: + """Post-rpc interceptor for get_agent_card + + DEPRECATED. Please use the `post_get_agent_card_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DataA2AService server but before + it is returned to user code. This `post_get_agent_card` interceptor runs + before the `post_get_agent_card_with_metadata` interceptor. + """ + return response + + def post_get_agent_card_with_metadata( + self, + response: data_a2a_service.AgentCard, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[data_a2a_service.AgentCard, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_agent_card + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DataA2AService server but before it is returned to user code. + + We recommend only using this `post_get_agent_card_with_metadata` + interceptor in new development instead of the `post_get_agent_card` interceptor. + When both interceptors are used, this `post_get_agent_card_with_metadata` interceptor runs after the + `post_get_agent_card` interceptor. The (possibly modified) response returned by + `post_get_agent_card` will be passed to + `post_get_agent_card_with_metadata`. + """ + return response, metadata + + def pre_send_message( + self, + request: data_a2a_service.SendMessageRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_a2a_service.SendMessageRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for send_message + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataA2AService server. + """ + return request, metadata + + def post_send_message( + self, response: data_a2a_service.SendMessageResponse + ) -> data_a2a_service.SendMessageResponse: + """Post-rpc interceptor for send_message + + DEPRECATED. Please use the `post_send_message_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DataA2AService server but before + it is returned to user code. This `post_send_message` interceptor runs + before the `post_send_message_with_metadata` interceptor. + """ + return response + + def post_send_message_with_metadata( + self, + response: data_a2a_service.SendMessageResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_a2a_service.SendMessageResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for send_message + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DataA2AService server but before it is returned to user code. + + We recommend only using this `post_send_message_with_metadata` + interceptor in new development instead of the `post_send_message` interceptor. + When both interceptors are used, this `post_send_message_with_metadata` interceptor runs after the + `post_send_message` interceptor. The (possibly modified) response returned by + `post_send_message` will be passed to + `post_send_message_with_metadata`. + """ + return response, metadata + + def pre_send_streaming_message( + self, + request: data_a2a_service.SendMessageRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_a2a_service.SendMessageRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for send_streaming_message + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataA2AService server. + """ + return request, metadata + + def post_send_streaming_message( + self, response: rest_streaming.ResponseIterator + ) -> rest_streaming.ResponseIterator: + """Post-rpc interceptor for send_streaming_message + + DEPRECATED. Please use the `post_send_streaming_message_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DataA2AService server but before + it is returned to user code. This `post_send_streaming_message` interceptor runs + before the `post_send_streaming_message_with_metadata` interceptor. + """ + return response + + def post_send_streaming_message_with_metadata( + self, + response: rest_streaming.ResponseIterator, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + rest_streaming.ResponseIterator, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for send_streaming_message + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DataA2AService server but before it is returned to user code. + + We recommend only using this `post_send_streaming_message_with_metadata` + interceptor in new development instead of the `post_send_streaming_message` interceptor. + When both interceptors are used, this `post_send_streaming_message_with_metadata` interceptor runs after the + `post_send_streaming_message` interceptor. The (possibly modified) response returned by + `post_send_streaming_message` will be passed to + `post_send_streaming_message_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataA2AService server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the DataA2AService server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataA2AService server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the DataA2AService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataA2AService 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 DataA2AService server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataA2AService 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 DataA2AService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataA2AService 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 DataA2AService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataA2AService 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 DataA2AService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DataA2AServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DataA2AServiceRestInterceptor + + +class DataA2AServiceRestTransport(_BaseDataA2AServiceRestTransport): + """REST backend synchronous transport for DataA2AService. + + DataA2AService defines the Agent-to-Agent (A2A) protocol + service for Gemini Data Analytics. + + 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 = "geminidataanalytics.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[DataA2AServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'geminidataanalytics.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + 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. + interceptor (Optional[DataA2AServiceRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DataA2AServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetAgentCard( + _BaseDataA2AServiceRestTransport._BaseGetAgentCard, DataA2AServiceRestStub + ): + def __hash__(self): + return hash("DataA2AServiceRestTransport.GetAgentCard") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: data_a2a_service.GetAgentCardRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_a2a_service.AgentCard: + r"""Call the get agent card method over HTTP. + + Args: + request (~.data_a2a_service.GetAgentCardRequest): + The request object. Request message for GetAgentCard. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.data_a2a_service.AgentCard: + AgentCard conveys key information + about an agent. + + """ + + http_options = ( + _BaseDataA2AServiceRestTransport._BaseGetAgentCard._get_http_options() + ) + request, metadata = self._interceptor.pre_get_agent_card(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataA2AServiceRestTransport._BaseGetAgentCard, + "_BaseGetAgentCard__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1beta.DataA2AServiceClient.GetAgentCard", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": "GetAgentCard", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataA2AServiceRestTransport._GetAgentCard._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = data_a2a_service.AgentCard() + pb_resp = data_a2a_service.AgentCard.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_agent_card(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_agent_card_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = data_a2a_service.AgentCard.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1beta.DataA2AServiceClient.get_agent_card", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": "GetAgentCard", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SendMessage( + _BaseDataA2AServiceRestTransport._BaseSendMessage, DataA2AServiceRestStub + ): + def __hash__(self): + return hash("DataA2AServiceRestTransport.SendMessage") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: data_a2a_service.SendMessageRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_a2a_service.SendMessageResponse: + r"""Call the send message method over HTTP. + + Args: + request (~.data_a2a_service.SendMessageRequest): + The request object. Request message for SendMessage and + SendStreamingMessage. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.data_a2a_service.SendMessageResponse: + Response message for SendMessage. + """ + + http_options = ( + _BaseDataA2AServiceRestTransport._BaseSendMessage._get_http_options() + ) + request, metadata = self._interceptor.pre_send_message(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataA2AServiceRestTransport._BaseSendMessage, + "_BaseSendMessage__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1beta.DataA2AServiceClient.SendMessage", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": "SendMessage", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataA2AServiceRestTransport._SendMessage._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = data_a2a_service.SendMessageResponse() + pb_resp = data_a2a_service.SendMessageResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_send_message(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_send_message_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = data_a2a_service.SendMessageResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1beta.DataA2AServiceClient.send_message", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": "SendMessage", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SendStreamingMessage( + _BaseDataA2AServiceRestTransport._BaseSendStreamingMessage, + DataA2AServiceRestStub, + ): + def __hash__(self): + return hash("DataA2AServiceRestTransport.SendStreamingMessage") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + stream=True, + ) + return response + + def __call__( + self, + request: data_a2a_service.SendMessageRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> rest_streaming.ResponseIterator: + r"""Call the send streaming message method over HTTP. + + Args: + request (~.data_a2a_service.SendMessageRequest): + The request object. Request message for SendMessage and + SendStreamingMessage. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.data_a2a_service.StreamResponse: + The stream response for a message. + """ + + http_options = _BaseDataA2AServiceRestTransport._BaseSendStreamingMessage._get_http_options() + request, metadata = self._interceptor.pre_send_streaming_message( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataA2AServiceRestTransport._BaseSendStreamingMessage, + "_BaseSendStreamingMessage__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1beta.DataA2AServiceClient.SendStreamingMessage", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": "SendStreamingMessage", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataA2AServiceRestTransport._SendStreamingMessage._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = rest_streaming.ResponseIterator( + response, data_a2a_service.StreamResponse + ) + + resp = self._interceptor.post_send_streaming_message(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_send_streaming_message_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + http_response = { + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1beta.DataA2AServiceClient.send_streaming_message", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": "SendStreamingMessage", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_agent_card( + self, + ) -> Callable[[data_a2a_service.GetAgentCardRequest], data_a2a_service.AgentCard]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAgentCard(self._session, self._host, self._interceptor) # type: ignore + + @property + def send_message( + self, + ) -> Callable[ + [data_a2a_service.SendMessageRequest], data_a2a_service.SendMessageResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SendMessage(self._session, self._host, self._interceptor) # type: ignore + + @property + def send_streaming_message( + self, + ) -> Callable[ + [data_a2a_service.SendMessageRequest], data_a2a_service.StreamResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SendStreamingMessage(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation( + _BaseDataA2AServiceRestTransport._BaseGetLocation, DataA2AServiceRestStub + ): + def __hash__(self): + return hash("DataA2AServiceRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = ( + _BaseDataA2AServiceRestTransport._BaseGetLocation._get_http_options() + ) + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataA2AServiceRestTransport._BaseGetLocation, + "_BaseGetLocation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1beta.DataA2AServiceClient.GetLocation", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataA2AServiceRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1beta.DataA2AServiceAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations( + _BaseDataA2AServiceRestTransport._BaseListLocations, DataA2AServiceRestStub + ): + def __hash__(self): + return hash("DataA2AServiceRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = ( + _BaseDataA2AServiceRestTransport._BaseListLocations._get_http_options() + ) + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataA2AServiceRestTransport._BaseListLocations, + "_BaseListLocations__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1beta.DataA2AServiceClient.ListLocations", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataA2AServiceRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1beta.DataA2AServiceAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseDataA2AServiceRestTransport._BaseCancelOperation, DataA2AServiceRestStub + ): + def __hash__(self): + return hash("DataA2AServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseDataA2AServiceRestTransport._BaseCancelOperation._get_http_options() + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataA2AServiceRestTransport._BaseCancelOperation, + "_BaseCancelOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1beta.DataA2AServiceClient.CancelOperation", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataA2AServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation( + _BaseDataA2AServiceRestTransport._BaseDeleteOperation, DataA2AServiceRestStub + ): + def __hash__(self): + return hash("DataA2AServiceRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseDataA2AServiceRestTransport._BaseDeleteOperation._get_http_options() + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataA2AServiceRestTransport._BaseDeleteOperation, + "_BaseDeleteOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1beta.DataA2AServiceClient.DeleteOperation", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataA2AServiceRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseDataA2AServiceRestTransport._BaseGetOperation, DataA2AServiceRestStub + ): + def __hash__(self): + return hash("DataA2AServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseDataA2AServiceRestTransport._BaseGetOperation._get_http_options() + ) + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataA2AServiceRestTransport._BaseGetOperation, + "_BaseGetOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1beta.DataA2AServiceClient.GetOperation", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataA2AServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1beta.DataA2AServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseDataA2AServiceRestTransport._BaseListOperations, DataA2AServiceRestStub + ): + def __hash__(self): + return hash("DataA2AServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = ( + _BaseDataA2AServiceRestTransport._BaseListOperations._get_http_options() + ) + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataA2AServiceRestTransport._BaseListOperations, + "_BaseListOperations__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1beta.DataA2AServiceClient.ListOperations", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataA2AServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1beta.DataA2AServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("DataA2AServiceRestTransport",) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/rest_base.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/rest_base.py new file mode 100644 index 000000000000..60cc17adf5c9 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_a2a_service/transports/rest_base.py @@ -0,0 +1,240 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.geminidataanalytics_v1beta.types import data_a2a_service + +from .base import DEFAULT_CLIENT_INFO, DataA2AServiceTransport + + +class _BaseDataA2AServiceRestTransport(DataA2AServiceTransport): + """Base REST backend transport for DataA2AService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "geminidataanalytics.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'geminidataanalytics.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseGetAgentCard: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/a2a/{tenant=projects/*/locations/*/agents/*}/v1/card", + }, + { + "method": "get", + "uri": "/v1beta/a2a/{tenant=projects/*/locations/*/dataAgents/*}/v1/card", + }, + ] + return http_options + + class _BaseSendMessage: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/a2a/{tenant=projects/*/locations/*/agents/*}/v1/message:send", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/a2a/{tenant=projects/*/locations/*/dataAgents/*}/v1/message:send", + "body": "*", + }, + ] + return http_options + + class _BaseSendStreamingMessage: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/a2a/{tenant=projects/*/locations/*/agents/*}/v1/message:stream", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta/a2a/{tenant=projects/*/locations/*/dataAgents/*}/v1/message:stream", + "body": "*", + }, + ] + return http_options + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}", + }, + ] + return http_options + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*}/locations", + }, + ] + return http_options + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + +__all__ = ("_BaseDataA2AServiceRestTransport",) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/async_client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/async_client.py index 07e4128890c1..f3422d496c24 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/async_client.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/async_client.py @@ -59,6 +59,7 @@ data_agent, data_agent_service, data_analytics_agent, + datasource, ) from google.cloud.geminidataanalytics_v1beta.types import data_agent as gcg_data_agent @@ -1730,6 +1731,290 @@ async def sample_set_iam_policy(): # Done; return the response. return response + async def set_agent_ops_observability( + self, + request: Optional[ + Union[data_agent_service.SetAgentOpsObservabilityRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + telemetry_enabled: Optional[bool] = None, + data_source_type: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Enables/Disables required GCP services and configures + AgentOps observability settings calling the Admin + Settings executable node to update the AgentOps + Observability feature. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1beta + + async def sample_set_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1beta.DataAgentServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.SetAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + operation = await client.set_agent_ops_observability(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.geminidataanalytics_v1beta.types.SetAgentOpsObservabilityRequest, dict]]): + The request object. Request for SetAgentOpsObservability. + parent (:class:`str`): + Required. Parent value for + SetAgentOpsObservabilityRequest. Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + telemetry_enabled (:class:`bool`): + Optional. Whether to enable or disable AgentOps + observability. When update_mask is provided, this field + is ignored unless specified in the mask. + + This corresponds to the ``telemetry_enabled`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_source_type (:class:`str`): + Required. The data source type for + which to set observability settings. + Examples: "bigquery", "looker" + + This corresponds to the ``data_source_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.geminidataanalytics_v1beta.types.SetAgentOpsObservabilityResponse` + Response for SetAgentOpsObservability. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, telemetry_enabled, data_source_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, data_agent_service.SetAgentOpsObservabilityRequest): + request = data_agent_service.SetAgentOpsObservabilityRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if telemetry_enabled is not None: + request.telemetry_enabled = telemetry_enabled + if data_source_type is not None: + request.data_source_type = data_source_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.set_agent_ops_observability + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + data_agent_service.SetAgentOpsObservabilityResponse, + metadata_type=data_agent_service.SetAgentOpsObservabilityMetadata, + ) + + # Done; return the response. + return response + + async def retrieve_agent_ops_observability( + self, + request: Optional[ + Union[data_agent_service.RetrieveAgentOpsObservabilityRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + data_source_type: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_agent_service.RetrieveAgentOpsObservabilityResponse: + r"""Gets AgentOps observability settings and status of + required services. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1beta + + async def sample_retrieve_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1beta.DataAgentServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.RetrieveAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + response = await client.retrieve_agent_ops_observability(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.geminidataanalytics_v1beta.types.RetrieveAgentOpsObservabilityRequest, dict]]): + The request object. Request for + RetrieveAgentOpsObservability. + parent (:class:`str`): + Required. Parent value for + RetrieveAgentOpsObservabilityRequest. + Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_source_type (:class:`str`): + Required. The data source type for + which to retrieve observability + settings. Examples: "bigquery", "looker" + + This corresponds to the ``data_source_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1beta.types.RetrieveAgentOpsObservabilityResponse: + Response for + RetrieveAgentOpsObservability. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, data_source_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, data_agent_service.RetrieveAgentOpsObservabilityRequest + ): + request = data_agent_service.RetrieveAgentOpsObservabilityRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if data_source_type is not None: + request.data_source_type = data_source_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.retrieve_agent_ops_observability + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def list_operations( self, request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/client.py index 7ca62552f67f..c4ca7088e451 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/client.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/client.py @@ -83,6 +83,7 @@ data_agent, data_agent_service, data_analytics_agent, + datasource, ) from google.cloud.geminidataanalytics_v1beta.types import data_agent as gcg_data_agent @@ -2027,6 +2028,288 @@ def sample_set_iam_policy(): # Done; return the response. return response + def set_agent_ops_observability( + self, + request: Optional[ + Union[data_agent_service.SetAgentOpsObservabilityRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + telemetry_enabled: Optional[bool] = None, + data_source_type: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Enables/Disables required GCP services and configures + AgentOps observability settings calling the Admin + Settings executable node to update the AgentOps + Observability feature. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1beta + + def sample_set_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1beta.DataAgentServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.SetAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + operation = client.set_agent_ops_observability(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.geminidataanalytics_v1beta.types.SetAgentOpsObservabilityRequest, dict]): + The request object. Request for SetAgentOpsObservability. + parent (str): + Required. Parent value for + SetAgentOpsObservabilityRequest. Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + telemetry_enabled (bool): + Optional. Whether to enable or disable AgentOps + observability. When update_mask is provided, this field + is ignored unless specified in the mask. + + This corresponds to the ``telemetry_enabled`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_source_type (str): + Required. The data source type for + which to set observability settings. + Examples: "bigquery", "looker" + + This corresponds to the ``data_source_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.geminidataanalytics_v1beta.types.SetAgentOpsObservabilityResponse` + Response for SetAgentOpsObservability. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, telemetry_enabled, data_source_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, data_agent_service.SetAgentOpsObservabilityRequest): + request = data_agent_service.SetAgentOpsObservabilityRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if telemetry_enabled is not None: + request.telemetry_enabled = telemetry_enabled + if data_source_type is not None: + request.data_source_type = data_source_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.set_agent_ops_observability + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + data_agent_service.SetAgentOpsObservabilityResponse, + metadata_type=data_agent_service.SetAgentOpsObservabilityMetadata, + ) + + # Done; return the response. + return response + + def retrieve_agent_ops_observability( + self, + request: Optional[ + Union[data_agent_service.RetrieveAgentOpsObservabilityRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + data_source_type: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_agent_service.RetrieveAgentOpsObservabilityResponse: + r"""Gets AgentOps observability settings and status of + required services. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1beta + + def sample_retrieve_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1beta.DataAgentServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.RetrieveAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + response = client.retrieve_agent_ops_observability(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.geminidataanalytics_v1beta.types.RetrieveAgentOpsObservabilityRequest, dict]): + The request object. Request for + RetrieveAgentOpsObservability. + parent (str): + Required. Parent value for + RetrieveAgentOpsObservabilityRequest. + Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_source_type (str): + Required. The data source type for + which to retrieve observability + settings. Examples: "bigquery", "looker" + + This corresponds to the ``data_source_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1beta.types.RetrieveAgentOpsObservabilityResponse: + Response for + RetrieveAgentOpsObservability. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, data_source_type] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, data_agent_service.RetrieveAgentOpsObservabilityRequest + ): + request = data_agent_service.RetrieveAgentOpsObservabilityRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if data_source_type is not None: + request.data_source_type = data_source_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.retrieve_agent_ops_observability + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "DataAgentServiceClient": return self diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/base.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/base.py index 43bf4a43f8d3..e6f62906e186 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/base.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/base.py @@ -201,6 +201,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.set_agent_ops_observability: gapic_v1.method.wrap_method( + self.set_agent_ops_observability, + default_timeout=None, + client_info=client_info, + ), + self.retrieve_agent_ops_observability: gapic_v1.method.wrap_method( + self.retrieve_agent_ops_observability, + default_timeout=None, + client_info=client_info, + ), self.get_location: gapic_v1.method.wrap_method( self.get_location, default_timeout=None, @@ -352,6 +362,27 @@ def set_iam_policy( ]: raise NotImplementedError() + @property + def set_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.SetAgentOpsObservabilityRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def retrieve_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.RetrieveAgentOpsObservabilityRequest], + Union[ + data_agent_service.RetrieveAgentOpsObservabilityResponse, + Awaitable[data_agent_service.RetrieveAgentOpsObservabilityResponse], + ], + ]: + raise NotImplementedError() + @property def list_operations( self, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/grpc.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/grpc.py index f938790be981..8e40f5b9150e 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/grpc.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/grpc.py @@ -656,6 +656,72 @@ def set_iam_policy( ) return self._stubs["set_iam_policy"] + @property + def set_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.SetAgentOpsObservabilityRequest], operations_pb2.Operation + ]: + r"""Return a callable for the set agent ops observability method over gRPC. + + Enables/Disables required GCP services and configures + AgentOps observability settings calling the Admin + Settings executable node to update the AgentOps + Observability feature. + + Returns: + Callable[[~.SetAgentOpsObservabilityRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_agent_ops_observability" not in self._stubs: + self._stubs["set_agent_ops_observability"] = ( + self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1beta.DataAgentService/SetAgentOpsObservability", + request_serializer=data_agent_service.SetAgentOpsObservabilityRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["set_agent_ops_observability"] + + @property + def retrieve_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.RetrieveAgentOpsObservabilityRequest], + data_agent_service.RetrieveAgentOpsObservabilityResponse, + ]: + r"""Return a callable for the retrieve agent ops + observability method over gRPC. + + Gets AgentOps observability settings and status of + required services. + + Returns: + Callable[[~.RetrieveAgentOpsObservabilityRequest], + ~.RetrieveAgentOpsObservabilityResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "retrieve_agent_ops_observability" not in self._stubs: + self._stubs["retrieve_agent_ops_observability"] = ( + self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1beta.DataAgentService/RetrieveAgentOpsObservability", + request_serializer=data_agent_service.RetrieveAgentOpsObservabilityRequest.serialize, + response_deserializer=data_agent_service.RetrieveAgentOpsObservabilityResponse.deserialize, + ) + ) + return self._stubs["retrieve_agent_ops_observability"] + def close(self): self._logged_channel.close() diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/grpc_asyncio.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/grpc_asyncio.py index 98162fabc88d..fb2492091b65 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/grpc_asyncio.py @@ -668,6 +668,73 @@ def set_iam_policy( ) return self._stubs["set_iam_policy"] + @property + def set_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.SetAgentOpsObservabilityRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the set agent ops observability method over gRPC. + + Enables/Disables required GCP services and configures + AgentOps observability settings calling the Admin + Settings executable node to update the AgentOps + Observability feature. + + Returns: + Callable[[~.SetAgentOpsObservabilityRequest], + 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 "set_agent_ops_observability" not in self._stubs: + self._stubs["set_agent_ops_observability"] = ( + self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1beta.DataAgentService/SetAgentOpsObservability", + request_serializer=data_agent_service.SetAgentOpsObservabilityRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["set_agent_ops_observability"] + + @property + def retrieve_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.RetrieveAgentOpsObservabilityRequest], + Awaitable[data_agent_service.RetrieveAgentOpsObservabilityResponse], + ]: + r"""Return a callable for the retrieve agent ops + observability method over gRPC. + + Gets AgentOps observability settings and status of + required services. + + Returns: + Callable[[~.RetrieveAgentOpsObservabilityRequest], + Awaitable[~.RetrieveAgentOpsObservabilityResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "retrieve_agent_ops_observability" not in self._stubs: + self._stubs["retrieve_agent_ops_observability"] = ( + self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1beta.DataAgentService/RetrieveAgentOpsObservability", + request_serializer=data_agent_service.RetrieveAgentOpsObservabilityRequest.serialize, + response_deserializer=data_agent_service.RetrieveAgentOpsObservabilityResponse.deserialize, + ) + ) + return self._stubs["retrieve_agent_ops_observability"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -726,6 +793,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.set_agent_ops_observability: self._wrap_method( + self.set_agent_ops_observability, + default_timeout=None, + client_info=client_info, + ), + self.retrieve_agent_ops_observability: self._wrap_method( + self.retrieve_agent_ops_observability, + default_timeout=None, + client_info=client_info, + ), self.get_location: self._wrap_method( self.get_location, default_timeout=None, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/rest.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/rest.py index 816926c3388c..bd00909708ee 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/rest.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/rest.py @@ -138,6 +138,22 @@ def post_list_data_agents(self, response): logging.log(f"Received response: {response}") return response + def pre_retrieve_agent_ops_observability(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_retrieve_agent_ops_observability(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_agent_ops_observability(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_agent_ops_observability(self, response): + logging.log(f"Received response: {response}") + return response + def pre_set_iam_policy(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -528,6 +544,107 @@ def post_list_data_agents_with_metadata( """ return response, metadata + def pre_retrieve_agent_ops_observability( + self, + request: data_agent_service.RetrieveAgentOpsObservabilityRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_agent_service.RetrieveAgentOpsObservabilityRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for retrieve_agent_ops_observability + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataAgentService server. + """ + return request, metadata + + def post_retrieve_agent_ops_observability( + self, response: data_agent_service.RetrieveAgentOpsObservabilityResponse + ) -> data_agent_service.RetrieveAgentOpsObservabilityResponse: + """Post-rpc interceptor for retrieve_agent_ops_observability + + DEPRECATED. Please use the `post_retrieve_agent_ops_observability_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DataAgentService server but before + it is returned to user code. This `post_retrieve_agent_ops_observability` interceptor runs + before the `post_retrieve_agent_ops_observability_with_metadata` interceptor. + """ + return response + + def post_retrieve_agent_ops_observability_with_metadata( + self, + response: data_agent_service.RetrieveAgentOpsObservabilityResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_agent_service.RetrieveAgentOpsObservabilityResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for retrieve_agent_ops_observability + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DataAgentService server but before it is returned to user code. + + We recommend only using this `post_retrieve_agent_ops_observability_with_metadata` + interceptor in new development instead of the `post_retrieve_agent_ops_observability` interceptor. + When both interceptors are used, this `post_retrieve_agent_ops_observability_with_metadata` interceptor runs after the + `post_retrieve_agent_ops_observability` interceptor. The (possibly modified) response returned by + `post_retrieve_agent_ops_observability` will be passed to + `post_retrieve_agent_ops_observability_with_metadata`. + """ + return response, metadata + + def pre_set_agent_ops_observability( + self, + request: data_agent_service.SetAgentOpsObservabilityRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_agent_service.SetAgentOpsObservabilityRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for set_agent_ops_observability + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataAgentService server. + """ + return request, metadata + + def post_set_agent_ops_observability( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for set_agent_ops_observability + + DEPRECATED. Please use the `post_set_agent_ops_observability_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DataAgentService server but before + it is returned to user code. This `post_set_agent_ops_observability` interceptor runs + before the `post_set_agent_ops_observability_with_metadata` interceptor. + """ + return response + + def post_set_agent_ops_observability_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for set_agent_ops_observability + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DataAgentService server but before it is returned to user code. + + We recommend only using this `post_set_agent_ops_observability_with_metadata` + interceptor in new development instead of the `post_set_agent_ops_observability` interceptor. + When both interceptors are used, this `post_set_agent_ops_observability_with_metadata` interceptor runs after the + `post_set_agent_ops_observability` interceptor. The (possibly modified) response returned by + `post_set_agent_ops_observability` will be passed to + `post_set_agent_ops_observability_with_metadata`. + """ + return response, metadata + def pre_set_iam_policy( self, request: iam_policy_pb2.SetIamPolicyRequest, @@ -2195,6 +2312,312 @@ def __call__( ) return resp + class _RetrieveAgentOpsObservability( + _BaseDataAgentServiceRestTransport._BaseRetrieveAgentOpsObservability, + DataAgentServiceRestStub, + ): + def __hash__(self): + return hash("DataAgentServiceRestTransport.RetrieveAgentOpsObservability") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: data_agent_service.RetrieveAgentOpsObservabilityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_agent_service.RetrieveAgentOpsObservabilityResponse: + r"""Call the retrieve agent ops + observability method over HTTP. + + Args: + request (~.data_agent_service.RetrieveAgentOpsObservabilityRequest): + The request object. Request for + RetrieveAgentOpsObservability. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.data_agent_service.RetrieveAgentOpsObservabilityResponse: + Response for + RetrieveAgentOpsObservability. + + """ + + http_options = _BaseDataAgentServiceRestTransport._BaseRetrieveAgentOpsObservability._get_http_options() + request, metadata = self._interceptor.pre_retrieve_agent_ops_observability( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataAgentServiceRestTransport._BaseRetrieveAgentOpsObservability, + "_BaseRetrieveAgentOpsObservability__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.RetrieveAgentOpsObservability", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", + "rpcName": "RetrieveAgentOpsObservability", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataAgentServiceRestTransport._RetrieveAgentOpsObservability._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = data_agent_service.RetrieveAgentOpsObservabilityResponse() + pb_resp = data_agent_service.RetrieveAgentOpsObservabilityResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_retrieve_agent_ops_observability(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_retrieve_agent_ops_observability_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = data_agent_service.RetrieveAgentOpsObservabilityResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.retrieve_agent_ops_observability", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", + "rpcName": "RetrieveAgentOpsObservability", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SetAgentOpsObservability( + _BaseDataAgentServiceRestTransport._BaseSetAgentOpsObservability, + DataAgentServiceRestStub, + ): + def __hash__(self): + return hash("DataAgentServiceRestTransport.SetAgentOpsObservability") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: data_agent_service.SetAgentOpsObservabilityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the set agent ops + observability method over HTTP. + + Args: + request (~.data_agent_service.SetAgentOpsObservabilityRequest): + The request object. Request for SetAgentOpsObservability. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseDataAgentServiceRestTransport._BaseSetAgentOpsObservability._get_http_options() + request, metadata = self._interceptor.pre_set_agent_ops_observability( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataAgentServiceRestTransport._BaseSetAgentOpsObservability, + "_BaseSetAgentOpsObservability__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.SetAgentOpsObservability", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", + "rpcName": "SetAgentOpsObservability", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + DataAgentServiceRestTransport._SetAgentOpsObservability._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_set_agent_ops_observability(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_set_agent_ops_observability_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.set_agent_ops_observability", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", + "rpcName": "SetAgentOpsObservability", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _SetIamPolicy( _BaseDataAgentServiceRestTransport._BaseSetIamPolicy, DataAgentServiceRestStub ): @@ -2794,6 +3217,31 @@ def list_data_agents( # In C++ this would require a dynamic_cast return self._ListDataAgents(self._session, self._host, self._interceptor) # type: ignore + @property + def retrieve_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.RetrieveAgentOpsObservabilityRequest], + data_agent_service.RetrieveAgentOpsObservabilityResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RetrieveAgentOpsObservability( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def set_agent_ops_observability( + self, + ) -> Callable[ + [data_agent_service.SetAgentOpsObservabilityRequest], 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._SetAgentOpsObservability( + self._session, self._host, self._interceptor + ) # type: ignore + @property def set_iam_policy( self, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/rest_base.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/rest_base.py index 63ad6dc029c8..1968c012d54f 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/rest_base.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_agent_service/transports/rest_base.py @@ -224,6 +224,41 @@ def _get_http_options(): ] return http_options + class _BaseRetrieveAgentOpsObservability: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "dataSourceType": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}:retrieveAgentOpsObservability", + }, + ] + return http_options + + class _BaseSetAgentOpsObservability: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*}/observabilitySettings:setAgentOpsObservability", + "body": "*", + }, + ] + return http_options + class _BaseSetIamPolicy: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/async_client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/async_client.py index 6096c16b1304..c983d837009b 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/async_client.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/async_client.py @@ -46,6 +46,7 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.struct_pb2 as struct_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore @@ -55,6 +56,7 @@ from google.cloud.geminidataanalytics_v1beta.types import ( conversation, data_chat_service, + usage, ) from google.cloud.geminidataanalytics_v1beta.types import ( conversation as gcg_conversation, @@ -642,6 +644,136 @@ async def sample_delete_conversation(): metadata=metadata, ) + async def update_conversation( + self, + request: Optional[ + Union[gcg_conversation.UpdateConversationRequest, dict] + ] = None, + *, + conversation: Optional[gcg_conversation.Conversation] = 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, Union[str, bytes]]] = (), + ) -> gcg_conversation.Conversation: + r"""Updates a conversation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1beta + + async def sample_update_conversation(): + # Create a client + client = geminidataanalytics_v1beta.DataChatServiceAsyncClient() + + # Initialize request argument(s) + conversation = geminidataanalytics_v1beta.Conversation() + conversation.agents = ['agents_value1', 'agents_value2'] + + request = geminidataanalytics_v1beta.UpdateConversationRequest( + conversation=conversation, + ) + + # Make the request + response = await client.update_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.geminidataanalytics_v1beta.types.UpdateConversationRequest, dict]]): + The request object. Request for updating a conversation. + conversation (:class:`google.cloud.geminidataanalytics_v1beta.types.Conversation`): + Required. The resource being updated. + This corresponds to the ``conversation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the Conversation resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields with non-default values + present in the request will be overwritten. If a + wildcard mask is provided, all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1beta.types.Conversation: + Message for a conversation. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [conversation, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcg_conversation.UpdateConversationRequest): + request = gcg_conversation.UpdateConversationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if conversation is not None: + request.conversation = conversation + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_conversation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("conversation.name", request.conversation.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def get_conversation( self, request: Optional[Union[conversation.GetConversationRequest, dict]] = None, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/client.py index a33c12f25144..b0ad4edcee84 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/client.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/client.py @@ -69,6 +69,7 @@ _LOGGER = std_logging.getLogger(__name__) +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.struct_pb2 as struct_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore @@ -78,6 +79,7 @@ from google.cloud.geminidataanalytics_v1beta.types import ( conversation, data_chat_service, + usage, ) from google.cloud.geminidataanalytics_v1beta.types import ( conversation as gcg_conversation, @@ -972,6 +974,133 @@ def sample_delete_conversation(): metadata=metadata, ) + def update_conversation( + self, + request: Optional[ + Union[gcg_conversation.UpdateConversationRequest, dict] + ] = None, + *, + conversation: Optional[gcg_conversation.Conversation] = 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, Union[str, bytes]]] = (), + ) -> gcg_conversation.Conversation: + r"""Updates a conversation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import geminidataanalytics_v1beta + + def sample_update_conversation(): + # Create a client + client = geminidataanalytics_v1beta.DataChatServiceClient() + + # Initialize request argument(s) + conversation = geminidataanalytics_v1beta.Conversation() + conversation.agents = ['agents_value1', 'agents_value2'] + + request = geminidataanalytics_v1beta.UpdateConversationRequest( + conversation=conversation, + ) + + # Make the request + response = client.update_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.geminidataanalytics_v1beta.types.UpdateConversationRequest, dict]): + The request object. Request for updating a conversation. + conversation (google.cloud.geminidataanalytics_v1beta.types.Conversation): + Required. The resource being updated. + This corresponds to the ``conversation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Conversation resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields with non-default values + present in the request will be overwritten. If a + wildcard mask is provided, all fields will be + overwritten. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.geminidataanalytics_v1beta.types.Conversation: + Message for a conversation. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [conversation, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcg_conversation.UpdateConversationRequest): + request = gcg_conversation.UpdateConversationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if conversation is not None: + request.conversation = conversation + 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_conversation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("conversation.name", request.conversation.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def get_conversation( self, request: Optional[Union[conversation.GetConversationRequest, dict]] = None, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/base.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/base.py index ba6e9bc94a17..9aad1b33c430 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/base.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/base.py @@ -164,6 +164,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.update_conversation: gapic_v1.method.wrap_method( + self.update_conversation, + default_timeout=None, + client_info=client_info, + ), self.get_conversation: gapic_v1.method.wrap_method( self.get_conversation, default_timeout=None, @@ -252,6 +257,15 @@ def delete_conversation( ]: raise NotImplementedError() + @property + def update_conversation( + self, + ) -> Callable[ + [gcg_conversation.UpdateConversationRequest], + Union[gcg_conversation.Conversation, Awaitable[gcg_conversation.Conversation]], + ]: + raise NotImplementedError() + @property def get_conversation( self, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/grpc.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/grpc.py index 3508fedf3e2a..e9e706fad072 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/grpc.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/grpc.py @@ -419,6 +419,34 @@ def delete_conversation( ) return self._stubs["delete_conversation"] + @property + def update_conversation( + self, + ) -> Callable[ + [gcg_conversation.UpdateConversationRequest], gcg_conversation.Conversation + ]: + r"""Return a callable for the update conversation method over gRPC. + + Updates a conversation. + + Returns: + Callable[[~.UpdateConversationRequest], + ~.Conversation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation" not in self._stubs: + self._stubs["update_conversation"] = self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1beta.DataChatService/UpdateConversation", + request_serializer=gcg_conversation.UpdateConversationRequest.serialize, + response_deserializer=gcg_conversation.Conversation.deserialize, + ) + return self._stubs["update_conversation"] + @property def get_conversation( self, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/grpc_asyncio.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/grpc_asyncio.py index 7df68e8da03c..9aeae835d3bc 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/grpc_asyncio.py @@ -430,6 +430,35 @@ def delete_conversation( ) return self._stubs["delete_conversation"] + @property + def update_conversation( + self, + ) -> Callable[ + [gcg_conversation.UpdateConversationRequest], + Awaitable[gcg_conversation.Conversation], + ]: + r"""Return a callable for the update conversation method over gRPC. + + Updates a conversation. + + Returns: + Callable[[~.UpdateConversationRequest], + Awaitable[~.Conversation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversation" not in self._stubs: + self._stubs["update_conversation"] = self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1beta.DataChatService/UpdateConversation", + request_serializer=gcg_conversation.UpdateConversationRequest.serialize, + response_deserializer=gcg_conversation.Conversation.deserialize, + ) + return self._stubs["update_conversation"] + @property def get_conversation( self, @@ -564,6 +593,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.update_conversation: self._wrap_method( + self.update_conversation, + default_timeout=None, + client_info=client_info, + ), self.get_conversation: self._wrap_method( self.get_conversation, default_timeout=None, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/rest.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/rest.py index 6c859f8a5294..c21b14d8b916 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/rest.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/rest.py @@ -133,6 +133,14 @@ def post_query_data(self, response): logging.log(f"Received response: {response}") return response + def pre_update_conversation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_conversation(self, response): + logging.log(f"Received response: {response}") + return response + transport = DataChatServiceRestTransport(interceptor=MyCustomDataChatServiceInterceptor()) client = DataChatServiceClient(transport=transport) @@ -448,6 +456,55 @@ def post_query_data_with_metadata( """ return response, metadata + def pre_update_conversation( + self, + request: gcg_conversation.UpdateConversationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcg_conversation.UpdateConversationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataChatService server. + """ + return request, metadata + + def post_update_conversation( + self, response: gcg_conversation.Conversation + ) -> gcg_conversation.Conversation: + """Post-rpc interceptor for update_conversation + + DEPRECATED. Please use the `post_update_conversation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DataChatService server but before + it is returned to user code. This `post_update_conversation` interceptor runs + before the `post_update_conversation_with_metadata` interceptor. + """ + return response + + def post_update_conversation_with_metadata( + self, + response: gcg_conversation.Conversation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcg_conversation.Conversation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_conversation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DataChatService server but before it is returned to user code. + + We recommend only using this `post_update_conversation_with_metadata` + interceptor in new development instead of the `post_update_conversation` interceptor. + When both interceptors are used, this `post_update_conversation_with_metadata` interceptor runs after the + `post_update_conversation` interceptor. The (possibly modified) response returned by + `post_update_conversation` will be passed to + `post_update_conversation_with_metadata`. + """ + return response, metadata + def pre_get_location( self, request: locations_pb2.GetLocationRequest, @@ -1682,6 +1739,154 @@ def __call__( ) return resp + class _UpdateConversation( + _BaseDataChatServiceRestTransport._BaseUpdateConversation, + DataChatServiceRestStub, + ): + def __hash__(self): + return hash("DataChatServiceRestTransport.UpdateConversation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gcg_conversation.UpdateConversationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcg_conversation.Conversation: + r"""Call the update conversation method over HTTP. + + Args: + request (~.gcg_conversation.UpdateConversationRequest): + The request object. Request for updating a conversation. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcg_conversation.Conversation: + Message for a conversation. + """ + + http_options = _BaseDataChatServiceRestTransport._BaseUpdateConversation._get_http_options() + request, metadata = self._interceptor.pre_update_conversation( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataChatServiceRestTransport._BaseUpdateConversation, + "_BaseUpdateConversation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.geminidataanalytics_v1beta.DataChatServiceClient.UpdateConversation", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataChatService", + "rpcName": "UpdateConversation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataChatServiceRestTransport._UpdateConversation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcg_conversation.Conversation() + pb_resp = gcg_conversation.Conversation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_conversation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_conversation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcg_conversation.Conversation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.geminidataanalytics_v1beta.DataChatServiceClient.update_conversation", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataChatService", + "rpcName": "UpdateConversation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + @property def chat( self, @@ -1746,6 +1951,16 @@ def query_data( # In C++ this would require a dynamic_cast return self._QueryData(self._session, self._host, self._interceptor) # type: ignore + @property + def update_conversation( + self, + ) -> Callable[ + [gcg_conversation.UpdateConversationRequest], gcg_conversation.Conversation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateConversation(self._session, self._host, self._interceptor) # type: ignore + @property def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/rest_base.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/rest_base.py index 64b79dc54fd0..a5788eee2711 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/rest_base.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/rest_base.py @@ -211,6 +211,23 @@ def _get_http_options(): ] return http_options + class _BaseUpdateConversation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{conversation.name=projects/*/locations/*/conversations/*}", + "body": "conversation", + }, + ] + return http_options + class _BaseGetLocation: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/__init__.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/__init__.py index 0ba5f6927ada..328d69174eb5 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/__init__.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/__init__.py @@ -27,6 +27,7 @@ Context, ConversationOptions, DatasourceOptions, + DynamicField, ExampleQuery, GlossaryTerm, LookerGoldenQuery, @@ -43,11 +44,52 @@ GetConversationRequest, ListConversationsRequest, ListConversationsResponse, + UpdateConversationRequest, ) from .credentials import ( Credentials, OAuthCredentials, ) +from .data_a2a_service import ( + A2AArtifact, + A2AMessage, + A2ATask, + AgentCapabilities, + AgentCard, + AgentCardSignature, + AgentExtension, + AgentInterface, + AgentProvider, + AgentSkill, + APIKeySecurityScheme, + AuthenticationInfo, + AuthorizationCodeOAuthFlow, + ClientCredentialsOAuthFlow, + DataPart, + FilePart, + GetAgentCardRequest, + HTTPAuthSecurityScheme, + ImplicitOAuthFlow, + MutualTlsSecurityScheme, + OAuth2SecurityScheme, + OAuthFlows, + OpenIdConnectSecurityScheme, + Part, + PasswordOAuthFlow, + PushNotificationConfig, + Role, + Security, + SecurityScheme, + SendMessageConfiguration, + SendMessageRequest, + SendMessageResponse, + StreamResponse, + StringList, + TaskArtifactUpdateEvent, + TaskState, + TaskStatus, + TaskStatusUpdateEvent, +) from .data_agent import ( DataAgent, ) @@ -60,6 +102,11 @@ ListDataAgentsRequest, ListDataAgentsResponse, OperationMetadata, + RetrieveAgentOpsObservabilityRequest, + RetrieveAgentOpsObservabilityResponse, + SetAgentOpsObservabilityMetadata, + SetAgentOpsObservabilityRequest, + SetAgentOpsObservabilityResponse, UpdateDataAgentRequest, ) from .data_analytics_agent import ( @@ -130,6 +177,9 @@ StudioDatasourceReference, StudioDatasourceReferences, ) +from .usage import ( + TokenUsage, +) __all__ = ( "AgentContextReference", @@ -143,6 +193,7 @@ "Context", "ConversationOptions", "DatasourceOptions", + "DynamicField", "ExampleQuery", "GlossaryTerm", "LookerGoldenQuery", @@ -157,8 +208,47 @@ "GetConversationRequest", "ListConversationsRequest", "ListConversationsResponse", + "UpdateConversationRequest", "Credentials", "OAuthCredentials", + "A2AArtifact", + "A2AMessage", + "A2ATask", + "AgentCapabilities", + "AgentCard", + "AgentCardSignature", + "AgentExtension", + "AgentInterface", + "AgentProvider", + "AgentSkill", + "APIKeySecurityScheme", + "AuthenticationInfo", + "AuthorizationCodeOAuthFlow", + "ClientCredentialsOAuthFlow", + "DataPart", + "FilePart", + "GetAgentCardRequest", + "HTTPAuthSecurityScheme", + "ImplicitOAuthFlow", + "MutualTlsSecurityScheme", + "OAuth2SecurityScheme", + "OAuthFlows", + "OpenIdConnectSecurityScheme", + "Part", + "PasswordOAuthFlow", + "PushNotificationConfig", + "Security", + "SecurityScheme", + "SendMessageConfiguration", + "SendMessageRequest", + "SendMessageResponse", + "StreamResponse", + "StringList", + "TaskArtifactUpdateEvent", + "TaskStatus", + "TaskStatusUpdateEvent", + "Role", + "TaskState", "DataAgent", "CreateDataAgentRequest", "DeleteDataAgentRequest", @@ -168,6 +258,11 @@ "ListDataAgentsRequest", "ListDataAgentsResponse", "OperationMetadata", + "RetrieveAgentOpsObservabilityRequest", + "RetrieveAgentOpsObservabilityResponse", + "SetAgentOpsObservabilityMetadata", + "SetAgentOpsObservabilityRequest", + "SetAgentOpsObservabilityResponse", "UpdateDataAgentRequest", "DataAnalyticsAgent", "AnalysisEvent", @@ -231,4 +326,5 @@ "StudioDatasourceReference", "StudioDatasourceReferences", "DataFilterType", + "TokenUsage", ) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/context.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/context.py index 383117bb720e..8bd5788126c1 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/context.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/context.py @@ -34,6 +34,7 @@ "MatchedQuery", "QueryParameterValues", "LookerGoldenQuery", + "DynamicField", "LookerQuery", "GlossaryTerm", "ConversationOptions", @@ -60,6 +61,9 @@ class Context(proto.Message): etc) and system instructions (e.g., answer like a Pirate) can help the model understand the business context around a user question. + + Must be at most 250,000 bytes (approx. 250,000 + characters for English text). datasource_references (google.cloud.geminidataanalytics_v1beta.types.DatasourceReferences): Required. Data sources that are available for answering the question. @@ -303,13 +307,18 @@ class ExampleQuery(proto.Message): Optional. The SQL query that should be generated to answer the natural language question. For example: "SELECT COUNT(\*) FROM orders WHERE order_date BETWEEN '2024-01-01' - AND '2024-01-31'". + AND '2024-01-31'" + + Must be at most 50,000 bytes (approx. 50,000 characters). This field is a member of `oneof`_ ``query``. natural_language_question (str): Optional. A natural language question that a user might ask. For example: "How many orders - were placed last month?". + were placed last month?" + + Must be at most 2,000 bytes (approx. 2,000 + characters). parameters (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.QueryParameter]): Optional. The list of query parameters. Example: The parameterized SQL query "SELECT \* FROM my_table WHERE id = @@ -426,7 +435,10 @@ class LookerGoldenQuery(proto.Message): natural_language_questions (MutableSequence[str]): Optional. Natural language questions that a user might ask. For example: "How many orders - were placed last month?". + were placed last month?" + + Must be at most 2,000 bytes per question + (approx. 2,000 characters). looker_query (google.cloud.geminidataanalytics_v1beta.types.LookerQuery): Optional. The Looker Query corresponding to the natural language questions. @@ -443,6 +455,170 @@ class LookerGoldenQuery(proto.Message): ) +class DynamicField(proto.Message): + r"""A dynamic field in Looker (Custom Dimension, Custom Measure, + or Table Calculation). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + category (str): + Optional. The type of dynamic field: dimension, measure, + table_calculation. Looker can use the category type to + specify the name of the dynamic field. However, Looker + Conversational Analytics keeps the category separate from + the name of the dynamic field. For more details, see + https://docs.cloud.google.com/looker/docs/reference/param-lookml-dashboard-table-chart#dynamic_fields. + + This field is a member of `oneof`_ ``_category``. + name (str): + Optional. The name of the dynamic field in + LookML. + + This field is a member of `oneof`_ ``_name``. + label (str): + Optional. The label defines the display name + of the dynamic field. + + This field is a member of `oneof`_ ``_label``. + based_on (str): + Optional. For custom measures, this + identifies the measure the field is based on. + + This field is a member of `oneof`_ ``_based_on``. + type_ (str): + Optional. For custom measures, this + identifies the type of aggregation (e.g. sum). + + This field is a member of `oneof`_ ``_type``. + description (str): + Optional. Description of the dynamic field. + + This field is a member of `oneof`_ ``_description``. + expression (str): + Optional. Looker expression to create a table + calculation. + + This field is a member of `oneof`_ ``_expression``. + filter_expression (str): + Optional. Looker expression to filter a base + measure. + + This field is a member of `oneof`_ ``_filter_expression``. + value_format (str): + Optional. Value format for the dynamic field. + + This field is a member of `oneof`_ ``_value_format``. + value_format_name (str): + Optional. Value format name for the dynamic + field if using a default named format. + + This field is a member of `oneof`_ ``_value_format_name``. + calculation_type (str): + Optional. Calculation type for table calculations. Refer to + https://docs.cloud.google.com/looker/docs/reference/param-lookml-dashboard-table-chart#calculation_type + for all possible values depending on the ``category`` of + dynamic field. + + This field is a member of `oneof`_ ``_calculation_type``. + args (MutableSequence[str]): + Optional. Arguments for custom groups, custom bins, or + shortcut calculations. For more details, refer to + https://docs.cloud.google.com/looker/docs/reference/param-lookml-dashboard-table-chart#args_for_custom_groups + kind_hint (str): + Optional. Identifies whether the dynamic + field returns a dimension or measure. + + This field is a member of `oneof`_ ``_kind_hint``. + type_hint (str): + Optional. Identifies the data type the + dynamic field's expression should produce. + + This field is a member of `oneof`_ ``_type_hint``. + is_disabled (bool): + Optional. Whether the dynamic field is + disabled. + + This field is a member of `oneof`_ ``_is_disabled``. + """ + + category: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + name: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + label: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + based_on: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + type_: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + description: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + expression: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) + filter_expression: str = proto.Field( + proto.STRING, + number=8, + optional=True, + ) + value_format: str = proto.Field( + proto.STRING, + number=9, + optional=True, + ) + value_format_name: str = proto.Field( + proto.STRING, + number=10, + optional=True, + ) + calculation_type: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) + args: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=12, + ) + kind_hint: str = proto.Field( + proto.STRING, + number=13, + optional=True, + ) + type_hint: str = proto.Field( + proto.STRING, + number=14, + optional=True, + ) + is_disabled: bool = proto.Field( + proto.BOOL, + number=15, + optional=True, + ) + + class LookerQuery(proto.Message): r"""Looker Query Object `Looker API documentation `__. @@ -469,6 +645,9 @@ class LookerQuery(proto.Message): Optional. Limit in the query. This field is a member of `oneof`_ ``_limit``. + dynamic_fields (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.DynamicField]): + Optional. The dynamic fields used in the + query. query_id (str): Optional. The primary identifier for the query resource in Looker, used for API operations. Maps to ``id`` (or @@ -537,6 +716,11 @@ class Filter(proto.Message): number=6, optional=True, ) + dynamic_fields: MutableSequence["DynamicField"] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message="DynamicField", + ) query_id: str = proto.Field( proto.STRING, number=10, @@ -556,13 +740,18 @@ class GlossaryTerm(proto.Message): display_name (str): Required. User friendly display name of the glossary term being defined. For example: "CTR", - "conversion rate", "pending". + "conversion rate", "pending" + + Must be at most 256 bytes. description (str): Required. The description or meaning of the term. For example: "Click-through rate", "The percentage of users who complete a desired action", "An order that is waiting to be - processed.". + processed." + + Must be at most 5,000 bytes (approx. 5,000 + characters). labels (MutableSequence[str]): Optional. A list of general purpose labels associated to this term. For example: ["click rate", "clickthrough", diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/conversation.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/conversation.py index 787f9a93d6a3..1c6e9e7fd0f8 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/conversation.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/conversation.py @@ -17,6 +17,7 @@ from typing import MutableMapping, MutableSequence +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import proto # type: ignore @@ -25,6 +26,7 @@ manifest={ "Conversation", "CreateConversationRequest", + "UpdateConversationRequest", "GetConversationRequest", "ListConversationsRequest", "ListConversationsResponse", @@ -69,6 +71,9 @@ class Conversation(proto.Message): that can be set by the client to tag a conversation (e.g. to filter conversations for specific surfaces/products). + title (str): + Optional. The display name for the + conversation (max 63 chars). kms_key (str): Optional. Customer managed encryption key (CMEK) to use for encrypting the Conversation resources. Encryption will @@ -78,11 +83,6 @@ class Conversation(proto.Message): projects/{project_id}/locations/{location}/keyRings/{key_ring_name}/cryptoKeys/{key_name}. This field is a member of `oneof`_ ``_kms_key``. - memory_paused (bool): - Optional. Whether memory is paused for this - conversation. - - This field is a member of `oneof`_ ``_memory_paused``. """ name: str = proto.Field( @@ -108,16 +108,15 @@ class Conversation(proto.Message): proto.STRING, number=9, ) + title: str = proto.Field( + proto.STRING, + number=6, + ) kms_key: str = proto.Field( proto.STRING, number=10, optional=True, ) - memory_paused: bool = proto.Field( - proto.BOOL, - number=11, - optional=True, - ) class CreateConversationRequest(proto.Message): @@ -162,6 +161,46 @@ class CreateConversationRequest(proto.Message): ) +class UpdateConversationRequest(proto.Message): + r"""Request for updating a conversation. + + Attributes: + conversation (google.cloud.geminidataanalytics_v1beta.types.Conversation): + Required. The resource being updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the Conversation resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields with non-default values present in the + request will be overwritten. If a wildcard mask is provided, + all fields will be overwritten. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + """ + + conversation: "Conversation" = proto.Field( + proto.MESSAGE, + number=1, + message="Conversation", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + class GetConversationRequest(proto.Message): r"""Request for getting a conversation based on parent and conversation id. diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_a2a_service.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_a2a_service.py new file mode 100644 index 000000000000..5e1352aaa167 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_a2a_service.py @@ -0,0 +1,1539 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.geminidataanalytics.v1beta", + manifest={ + "TaskState", + "Role", + "SendMessageConfiguration", + "A2ATask", + "TaskStatus", + "Part", + "FilePart", + "DataPart", + "A2AMessage", + "A2AArtifact", + "TaskStatusUpdateEvent", + "TaskArtifactUpdateEvent", + "PushNotificationConfig", + "AuthenticationInfo", + "AgentInterface", + "AgentCard", + "AgentProvider", + "AgentCapabilities", + "AgentExtension", + "AgentSkill", + "AgentCardSignature", + "StringList", + "Security", + "SecurityScheme", + "APIKeySecurityScheme", + "HTTPAuthSecurityScheme", + "OAuth2SecurityScheme", + "OpenIdConnectSecurityScheme", + "MutualTlsSecurityScheme", + "OAuthFlows", + "AuthorizationCodeOAuthFlow", + "ClientCredentialsOAuthFlow", + "ImplicitOAuthFlow", + "PasswordOAuthFlow", + "SendMessageRequest", + "GetAgentCardRequest", + "SendMessageResponse", + "StreamResponse", + }, +) + + +class TaskState(proto.Enum): + r"""The set of states a Task can be in. + + Values: + TASK_STATE_UNSPECIFIED (0): + Default unspecified task state. + TASK_STATE_SUBMITTED (1): + Represents the status that acknowledges a + task is created. + TASK_STATE_WORKING (2): + Represents the status that a task is + currently in progress. + TASK_STATE_COMPLETED (3): + Represents the status that a task is + completed. This is a terminal state. + TASK_STATE_FAILED (4): + Represents the status that a task has failed. + This is a terminal state. + TASK_STATE_CANCELLED (5): + Represents the status that a task was + cancelled before it finished. This is a terminal + state. + TASK_STATE_INPUT_REQUIRED (6): + Represents the status that the task requires + information to complete. This is an interrupted + state. + TASK_STATE_REJECTED (7): + Represents the status that a task has been + rejected by the agent. This is a terminal state. + TASK_STATE_AUTH_REQUIRED (8): + Represents the state that some authentication + is needed from the upstream client. + """ + + TASK_STATE_UNSPECIFIED = 0 + TASK_STATE_SUBMITTED = 1 + TASK_STATE_WORKING = 2 + TASK_STATE_COMPLETED = 3 + TASK_STATE_FAILED = 4 + TASK_STATE_CANCELLED = 5 + TASK_STATE_INPUT_REQUIRED = 6 + TASK_STATE_REJECTED = 7 + TASK_STATE_AUTH_REQUIRED = 8 + + +class Role(proto.Enum): + r"""Role indicates the sender of a message. + + Values: + ROLE_UNSPECIFIED (0): + Default unspecified role. + ROLE_USER (1): + USER role refers to communication from the + client to the server. + ROLE_AGENT (2): + AGENT role refers to communication from the + server to the client. + """ + + ROLE_UNSPECIFIED = 0 + ROLE_USER = 1 + ROLE_AGENT = 2 + + +class SendMessageConfiguration(proto.Message): + r"""Configuration of a send message request. + + Attributes: + accepted_output_modes (MutableSequence[str]): + Optional. The output modes that the agent is + expected to respond with. + push_notification (google.cloud.geminidataanalytics_v1beta.types.PushNotificationConfig): + Optional. A configuration of a webhook that + can be used to receive updates. + history_length (int): + Optional. The maximum number of messages to + include in the history. If 0, the history will + be unlimited. + blocking (bool): + Optional. If true, the message will be + blocking until the task is completed. If false, + the task will be returned immediately. + """ + + accepted_output_modes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + push_notification: "PushNotificationConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="PushNotificationConfig", + ) + history_length: int = proto.Field( + proto.INT32, + number=3, + ) + blocking: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class A2ATask(proto.Message): + r"""A2ATask is the core unit of action for A2A. It has a current + status and when results are created for the task they are stored + in the artifact. If there are multiple turns for a task, these + are stored in history. + + Attributes: + id (str): + Optional. Unique identifier (e.g. UUID) for + the task, generated by the server for a new + task. + context_id (str): + Optional. Unique identifier (e.g. UUID) for + the contextual collection of interactions (tasks + and messages). Created by the A2A server. + status (google.cloud.geminidataanalytics_v1beta.types.TaskStatus): + Optional. The current status of a Task, + including state and a message. + artifacts (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.A2AArtifact]): + Optional. A set of output artifacts for a + Task. + history (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.A2AMessage]): + Optional. The history of interactions from a + task. + metadata (google.protobuf.struct_pb2.Struct): + Optional. A key/value object to store custom + metadata about a task. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + context_id: str = proto.Field( + proto.STRING, + number=2, + ) + status: "TaskStatus" = proto.Field( + proto.MESSAGE, + number=3, + message="TaskStatus", + ) + artifacts: MutableSequence["A2AArtifact"] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="A2AArtifact", + ) + history: MutableSequence["A2AMessage"] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="A2AMessage", + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + + +class TaskStatus(proto.Message): + r"""A container for the status of a task. + + Attributes: + state (google.cloud.geminidataanalytics_v1beta.types.TaskState): + Output only. The current state of this task. + update (google.cloud.geminidataanalytics_v1beta.types.A2AMessage): + Optional. A message associated with the + status. + timestamp (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the status was + recorded. + """ + + state: "TaskState" = proto.Field( + proto.ENUM, + number=1, + enum="TaskState", + ) + update: "A2AMessage" = proto.Field( + proto.MESSAGE, + number=2, + message="A2AMessage", + ) + timestamp: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class Part(proto.Message): + r"""Part represents a container for a section of communication + content. Parts can be purely textual, some sort of file (image, + video, etc) or a structured data blob (i.e. JSON). + + 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: + text (str): + Plain text content. + + This field is a member of `oneof`_ ``part``. + file (google.cloud.geminidataanalytics_v1beta.types.FilePart): + File content payload. + + This field is a member of `oneof`_ ``part``. + data (google.cloud.geminidataanalytics_v1beta.types.DataPart): + Structured data content payload. + + This field is a member of `oneof`_ ``part``. + metadata (google.protobuf.struct_pb2.Struct): + Optional. Metadata associated with the part. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + oneof="part", + ) + file: "FilePart" = proto.Field( + proto.MESSAGE, + number=2, + oneof="part", + message="FilePart", + ) + data: "DataPart" = proto.Field( + proto.MESSAGE, + number=3, + oneof="part", + message="DataPart", + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + + +class FilePart(proto.Message): + r"""FilePart represents the different ways files can be provided. + + 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: + file_with_uri (str): + The URI pointing to the file. + + This field is a member of `oneof`_ ``file``. + file_with_bytes (bytes): + The raw bytes of the file. + + This field is a member of `oneof`_ ``file``. + mime_type (str): + Optional. The MIME type of the file. + name (str): + Optional. The name of the file. + """ + + file_with_uri: str = proto.Field( + proto.STRING, + number=1, + oneof="file", + ) + file_with_bytes: bytes = proto.Field( + proto.BYTES, + number=2, + oneof="file", + ) + mime_type: str = proto.Field( + proto.STRING, + number=3, + ) + name: str = proto.Field( + proto.STRING, + number=4, + ) + + +class DataPart(proto.Message): + r"""DataPart represents a structured blob. This is most commonly + a JSON payload. + + Attributes: + data (google.protobuf.struct_pb2.Struct): + Optional. The structured data payload. + """ + + data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=1, + message=struct_pb2.Struct, + ) + + +class A2AMessage(proto.Message): + r"""A2AMessage is one unit of communication between client and + server. + + Attributes: + message_id (str): + Optional. The unique identifier (e.g. UUID) + of the message. + context_id (str): + Optional. The context id of the message. + task_id (str): + Optional. The task id of the message. + role (google.cloud.geminidataanalytics_v1beta.types.Role): + Optional. A role for the message. + content (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.Part]): + Optional. Content is the container of the + message content. + metadata (google.protobuf.struct_pb2.Struct): + Optional. Any optional metadata to provide + along with the message. + extensions (MutableSequence[str]): + Optional. The URIs of extensions that are + present or contributed to this Message. + """ + + message_id: str = proto.Field( + proto.STRING, + number=1, + ) + context_id: str = proto.Field( + proto.STRING, + number=2, + ) + task_id: str = proto.Field( + proto.STRING, + number=3, + ) + role: "Role" = proto.Field( + proto.ENUM, + number=4, + enum="Role", + ) + content: MutableSequence["Part"] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="Part", + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + extensions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + +class A2AArtifact(proto.Message): + r"""A2AArtifact is the container for task completed results. + + Attributes: + artifact_id (str): + Optional. Unique identifier (e.g. UUID) for + the artifact. + name (str): + Optional. A human readable name for the + artifact. + description (str): + Optional. A human readable description of the + artifact, optional. + parts (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.Part]): + Optional. The content of the artifact. + metadata (google.protobuf.struct_pb2.Struct): + Optional. Optional metadata included with the + artifact. + extensions (MutableSequence[str]): + Optional. The URIs of extensions that are + present or contributed to this Artifact. + """ + + artifact_id: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + description: str = proto.Field( + proto.STRING, + number=4, + ) + parts: MutableSequence["Part"] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="Part", + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + extensions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + +class TaskStatusUpdateEvent(proto.Message): + r"""TaskStatusUpdateEvent is a delta event on a task indicating + that a task has changed. + + Attributes: + task_id (str): + Optional. The id of the task that is changed. + context_id (str): + Optional. The id of the context that the task + belongs to. + status (google.cloud.geminidataanalytics_v1beta.types.TaskStatus): + Optional. The new status of the task. + final (bool): + Optional. Whether this is the last status + update expected for this task. + metadata (google.protobuf.struct_pb2.Struct): + Optional. Optional metadata to associate with + the task update. + """ + + task_id: str = proto.Field( + proto.STRING, + number=1, + ) + context_id: str = proto.Field( + proto.STRING, + number=2, + ) + status: "TaskStatus" = proto.Field( + proto.MESSAGE, + number=3, + message="TaskStatus", + ) + final: bool = proto.Field( + proto.BOOL, + number=4, + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=5, + message=struct_pb2.Struct, + ) + + +class TaskArtifactUpdateEvent(proto.Message): + r"""TaskArtifactUpdateEvent represents a task delta where an + artifact has been generated. + + Attributes: + task_id (str): + Optional. The id of the task for this + artifact. + context_id (str): + Optional. The id of the context that this + task belongs to. + artifact (google.cloud.geminidataanalytics_v1beta.types.A2AArtifact): + Optional. The artifact itself. + append (bool): + Optional. Whether this should be appended to + a prior one produced. + last_chunk (bool): + Optional. Whether this represents the last + part of an artifact. + metadata (google.protobuf.struct_pb2.Struct): + Optional. Optional metadata associated with + the artifact update. + """ + + task_id: str = proto.Field( + proto.STRING, + number=1, + ) + context_id: str = proto.Field( + proto.STRING, + number=2, + ) + artifact: "A2AArtifact" = proto.Field( + proto.MESSAGE, + number=3, + message="A2AArtifact", + ) + append: bool = proto.Field( + proto.BOOL, + number=4, + ) + last_chunk: bool = proto.Field( + proto.BOOL, + number=5, + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + + +class PushNotificationConfig(proto.Message): + r"""Configuration for setting up push notifications for task + updates. + + Attributes: + id (str): + Optional. A unique identifier (e.g. UUID) for + this push notification. + url (str): + Optional. Url to send the notification to. + token (str): + Optional. Token unique for this task/session. + authentication (google.cloud.geminidataanalytics_v1beta.types.AuthenticationInfo): + Optional. Information about the + authentication to send with the notification. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + url: str = proto.Field( + proto.STRING, + number=2, + ) + token: str = proto.Field( + proto.STRING, + number=3, + ) + authentication: "AuthenticationInfo" = proto.Field( + proto.MESSAGE, + number=4, + message="AuthenticationInfo", + ) + + +class AuthenticationInfo(proto.Message): + r"""Defines authentication details, used for push notifications. + + Attributes: + schemes (MutableSequence[str]): + Optional. Supported authentication schemes - + e.g. Basic, Bearer, etc. + credentials (str): + Optional. Optional credentials. + """ + + schemes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + credentials: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AgentInterface(proto.Message): + r"""Defines additional transport information for the agent. + + Attributes: + url (str): + Optional. The url this interface is found at. + transport (str): + Optional. The transport supported at this + url. + tenant (str): + Optional. Tenant to be set in the request + when calling the agent. + """ + + url: str = proto.Field( + proto.STRING, + number=1, + ) + transport: str = proto.Field( + proto.STRING, + number=2, + ) + tenant: str = proto.Field( + proto.STRING, + number=3, + ) + + +class AgentCard(proto.Message): + r"""AgentCard conveys key information about an agent. + + Attributes: + protocol_version (str): + Optional. The version of the A2A protocol + this agent supports. + name (str): + Optional. A human readable name for the + agent. + description (str): + Optional. A description of the agent's domain + of action/solution space. + url (str): + Optional. A URL to the address the agent is + hosted at. + preferred_transport (str): + Optional. The transport of the preferred + endpoint. If empty, defaults to JSONRPC. + additional_interfaces (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.AgentInterface]): + Optional. Announcement of additional + supported transports. + provider (google.cloud.geminidataanalytics_v1beta.types.AgentProvider): + Optional. The service provider of the agent. + version (str): + Optional. The version of the agent. + documentation_url (str): + Optional. A url to provide additional + documentation about the agent. + capabilities (google.cloud.geminidataanalytics_v1beta.types.AgentCapabilities): + Optional. A2A Capability set supported by the + agent. + security_schemes (MutableMapping[str, google.cloud.geminidataanalytics_v1beta.types.SecurityScheme]): + The security scheme details used for + authenticating with this agent. + security (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.Security]): + Security requirements for contacting the + agent. + default_input_modes (MutableSequence[str]): + Optional. The set of interaction modes that + the agent supports across all skills. + default_output_modes (MutableSequence[str]): + Optional. The mime types supported as outputs + from this agent. + skills (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.AgentSkill]): + Optional. Skills represent a unit of ability + an agent can perform. + supports_authenticated_extended_card (bool): + Optional. Whether the agent supports + providing an extended agent card when the user + is authenticated. + signatures (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.AgentCardSignature]): + Optional. JSON Web Signatures computed for + this AgentCard. + icon_url (str): + Optional. An optional URL to an icon for the + agent. + """ + + protocol_version: str = proto.Field( + proto.STRING, + number=16, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + url: str = proto.Field( + proto.STRING, + number=3, + ) + preferred_transport: str = proto.Field( + proto.STRING, + number=14, + ) + additional_interfaces: MutableSequence["AgentInterface"] = proto.RepeatedField( + proto.MESSAGE, + number=15, + message="AgentInterface", + ) + provider: "AgentProvider" = proto.Field( + proto.MESSAGE, + number=4, + message="AgentProvider", + ) + version: str = proto.Field( + proto.STRING, + number=5, + ) + documentation_url: str = proto.Field( + proto.STRING, + number=6, + ) + capabilities: "AgentCapabilities" = proto.Field( + proto.MESSAGE, + number=7, + message="AgentCapabilities", + ) + security_schemes: MutableMapping[str, "SecurityScheme"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=8, + message="SecurityScheme", + ) + security: MutableSequence["Security"] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message="Security", + ) + default_input_modes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + default_output_modes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=11, + ) + skills: MutableSequence["AgentSkill"] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message="AgentSkill", + ) + supports_authenticated_extended_card: bool = proto.Field( + proto.BOOL, + number=13, + ) + signatures: MutableSequence["AgentCardSignature"] = proto.RepeatedField( + proto.MESSAGE, + number=17, + message="AgentCardSignature", + ) + icon_url: str = proto.Field( + proto.STRING, + number=18, + ) + + +class AgentProvider(proto.Message): + r"""Represents information about the service provider of an + agent. + + Attributes: + url (str): + Optional. The provider's reference url. + organization (str): + Optional. The provider's organization name. + """ + + url: str = proto.Field( + proto.STRING, + number=1, + ) + organization: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AgentCapabilities(proto.Message): + r"""Defines the A2A feature set supported by the agent. + + Attributes: + streaming (bool): + Optional. If the agent will support streaming + responses. + push_notifications (bool): + Optional. If the agent can send push + notifications to the client's webhook. + extensions (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.AgentExtension]): + Optional. Extensions supported by this agent. + """ + + streaming: bool = proto.Field( + proto.BOOL, + number=1, + ) + push_notifications: bool = proto.Field( + proto.BOOL, + number=2, + ) + extensions: MutableSequence["AgentExtension"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="AgentExtension", + ) + + +class AgentExtension(proto.Message): + r"""A declaration of an extension supported by an Agent. + + Attributes: + uri (str): + Optional. The URI of the extension. + description (str): + Optional. A description of how this agent + uses this extension. + required (bool): + Optional. Whether the client must follow + specific requirements of the extension. + params (google.protobuf.struct_pb2.Struct): + Optional. Optional configuration for the + extension. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + required: bool = proto.Field( + proto.BOOL, + number=3, + ) + params: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + + +class AgentSkill(proto.Message): + r"""AgentSkill represents a unit of action/solution that the + agent can perform. + + Attributes: + id (str): + Optional. Unique identifier of the skill + within this agent. + name (str): + Optional. A human readable name for the + skill. + description (str): + Optional. A human readable description of the + skill details and behaviors. + tags (MutableSequence[str]): + Optional. A set of tags for the skill to + enhance categorization/utilization. + examples (MutableSequence[str]): + Optional. A set of example queries that this + skill is designed to address. + input_modes (MutableSequence[str]): + Optional. Possible input modalities + supported. + output_modes (MutableSequence[str]): + Optional. Possible output modalities + produced. + security (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.Security]): + Security schemes necessary for the agent to + leverage this skill. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + examples: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + input_modes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + output_modes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + security: MutableSequence["Security"] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message="Security", + ) + + +class AgentCardSignature(proto.Message): + r"""AgentCardSignature represents a JWS signature of an + AgentCard. + + Attributes: + protected (str): + Required. The protected JWS header for the + signature. Base64url-encoded. + signature (str): + Required. The computed signature, + base64url-encoded. + header (google.protobuf.struct_pb2.Struct): + Optional. The unprotected JWS header values. + """ + + protected: str = proto.Field( + proto.STRING, + number=1, + ) + signature: str = proto.Field( + proto.STRING, + number=2, + ) + header: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + + +class StringList(proto.Message): + r"""StringList is a wrapper for a repeated list of strings. + + Attributes: + list_ (MutableSequence[str]): + The list of strings. + """ + + list_: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class Security(proto.Message): + r"""Security requirements for contacting the agent. + + Attributes: + schemes (MutableMapping[str, google.cloud.geminidataanalytics_v1beta.types.StringList]): + Map of scheme names to lists of scopes or + configurations. + """ + + schemes: MutableMapping[str, "StringList"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message="StringList", + ) + + +class SecurityScheme(proto.Message): + r"""SecurityScheme defines a security scheme for contacting the + agent. + + 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: + api_key_security_scheme (google.cloud.geminidataanalytics_v1beta.types.APIKeySecurityScheme): + API key security scheme. + + This field is a member of `oneof`_ ``scheme``. + http_auth_security_scheme (google.cloud.geminidataanalytics_v1beta.types.HTTPAuthSecurityScheme): + HTTP authentication security scheme. + + This field is a member of `oneof`_ ``scheme``. + oauth2_security_scheme (google.cloud.geminidataanalytics_v1beta.types.OAuth2SecurityScheme): + OAuth2 security scheme. + + This field is a member of `oneof`_ ``scheme``. + open_id_connect_security_scheme (google.cloud.geminidataanalytics_v1beta.types.OpenIdConnectSecurityScheme): + OpenID Connect security scheme. + + This field is a member of `oneof`_ ``scheme``. + mtls_security_scheme (google.cloud.geminidataanalytics_v1beta.types.MutualTlsSecurityScheme): + Mutual TLS security scheme. + + This field is a member of `oneof`_ ``scheme``. + """ + + api_key_security_scheme: "APIKeySecurityScheme" = proto.Field( + proto.MESSAGE, + number=1, + oneof="scheme", + message="APIKeySecurityScheme", + ) + http_auth_security_scheme: "HTTPAuthSecurityScheme" = proto.Field( + proto.MESSAGE, + number=2, + oneof="scheme", + message="HTTPAuthSecurityScheme", + ) + oauth2_security_scheme: "OAuth2SecurityScheme" = proto.Field( + proto.MESSAGE, + number=3, + oneof="scheme", + message="OAuth2SecurityScheme", + ) + open_id_connect_security_scheme: "OpenIdConnectSecurityScheme" = proto.Field( + proto.MESSAGE, + number=4, + oneof="scheme", + message="OpenIdConnectSecurityScheme", + ) + mtls_security_scheme: "MutualTlsSecurityScheme" = proto.Field( + proto.MESSAGE, + number=5, + oneof="scheme", + message="MutualTlsSecurityScheme", + ) + + +class APIKeySecurityScheme(proto.Message): + r"""APIKeySecurityScheme defines an API key security scheme. + + Attributes: + description (str): + Optional. Description of this security + scheme. + location (str): + Optional. Location of the API key, valid + values are "query", "header", or "cookie". + name (str): + Optional. Name of the header, query or cookie + parameter to be used. + """ + + description: str = proto.Field( + proto.STRING, + number=1, + ) + location: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + +class HTTPAuthSecurityScheme(proto.Message): + r"""HTTPAuthSecurityScheme defines an HTTP authentication + security scheme. + + Attributes: + description (str): + Optional. Description of this security + scheme. + scheme (str): + Optional. The name of the HTTP Authentication + scheme to be used in the Authorization header. + bearer_format (str): + Optional. A hint to the client to identify + how the bearer token is formatted. + """ + + description: str = proto.Field( + proto.STRING, + number=1, + ) + scheme: str = proto.Field( + proto.STRING, + number=2, + ) + bearer_format: str = proto.Field( + proto.STRING, + number=3, + ) + + +class OAuth2SecurityScheme(proto.Message): + r"""OAuth2SecurityScheme defines an OAuth2 security scheme. + + Attributes: + description (str): + Optional. Description of this security + scheme. + flows (google.cloud.geminidataanalytics_v1beta.types.OAuthFlows): + Optional. An object containing configuration + information for the flow types supported. + oauth2_metadata_url (str): + Optional. URL to the oauth2 authorization + server metadata. + """ + + description: str = proto.Field( + proto.STRING, + number=1, + ) + flows: "OAuthFlows" = proto.Field( + proto.MESSAGE, + number=2, + message="OAuthFlows", + ) + oauth2_metadata_url: str = proto.Field( + proto.STRING, + number=3, + ) + + +class OpenIdConnectSecurityScheme(proto.Message): + r"""OpenIdConnectSecurityScheme defines an OpenID Connect + security scheme. + + Attributes: + description (str): + Optional. Description of this security + scheme. + open_id_connect_url (str): + Optional. Well-known URL to discover the + OpenID Connect provider metadata. + """ + + description: str = proto.Field( + proto.STRING, + number=1, + ) + open_id_connect_url: str = proto.Field( + proto.STRING, + number=2, + ) + + +class MutualTlsSecurityScheme(proto.Message): + r"""MutualTlsSecurityScheme defines a Mutual TLS security scheme. + + Attributes: + description (str): + Optional. Description of this security + scheme. + """ + + description: str = proto.Field( + proto.STRING, + number=1, + ) + + +class OAuthFlows(proto.Message): + r"""OAuthFlows contains configuration information for supported + OAuth flows. + + 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: + authorization_code (google.cloud.geminidataanalytics_v1beta.types.AuthorizationCodeOAuthFlow): + Authorization code flow. + + This field is a member of `oneof`_ ``flow``. + client_credentials (google.cloud.geminidataanalytics_v1beta.types.ClientCredentialsOAuthFlow): + Client credentials flow. + + This field is a member of `oneof`_ ``flow``. + implicit (google.cloud.geminidataanalytics_v1beta.types.ImplicitOAuthFlow): + Implicit flow. + + This field is a member of `oneof`_ ``flow``. + password (google.cloud.geminidataanalytics_v1beta.types.PasswordOAuthFlow): + Resource owner password credentials flow. + + This field is a member of `oneof`_ ``flow``. + """ + + authorization_code: "AuthorizationCodeOAuthFlow" = proto.Field( + proto.MESSAGE, + number=1, + oneof="flow", + message="AuthorizationCodeOAuthFlow", + ) + client_credentials: "ClientCredentialsOAuthFlow" = proto.Field( + proto.MESSAGE, + number=2, + oneof="flow", + message="ClientCredentialsOAuthFlow", + ) + implicit: "ImplicitOAuthFlow" = proto.Field( + proto.MESSAGE, + number=3, + oneof="flow", + message="ImplicitOAuthFlow", + ) + password: "PasswordOAuthFlow" = proto.Field( + proto.MESSAGE, + number=4, + oneof="flow", + message="PasswordOAuthFlow", + ) + + +class AuthorizationCodeOAuthFlow(proto.Message): + r"""AuthorizationCodeOAuthFlow defines an authorization code + OAuth flow. + + Attributes: + authorization_url (str): + Optional. The authorization URL to be used + for this flow. + token_url (str): + Optional. The token URL to be used for this + flow. + refresh_url (str): + Optional. The URL to be used for obtaining + refresh tokens. + scopes (MutableMapping[str, str]): + The available scopes for the OAuth2 security + scheme. + """ + + authorization_url: str = proto.Field( + proto.STRING, + number=1, + ) + token_url: str = proto.Field( + proto.STRING, + number=2, + ) + refresh_url: str = proto.Field( + proto.STRING, + number=3, + ) + scopes: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + + +class ClientCredentialsOAuthFlow(proto.Message): + r"""ClientCredentialsOAuthFlow defines a client credentials OAuth + flow. + + Attributes: + token_url (str): + Optional. The token URL to be used for this + flow. + refresh_url (str): + Optional. The URL to be used for obtaining + refresh tokens. + scopes (MutableMapping[str, str]): + The available scopes for the OAuth2 security + scheme. + """ + + token_url: str = proto.Field( + proto.STRING, + number=1, + ) + refresh_url: str = proto.Field( + proto.STRING, + number=2, + ) + scopes: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + + +class ImplicitOAuthFlow(proto.Message): + r"""ImplicitOAuthFlow defines an implicit OAuth flow. + + Attributes: + authorization_url (str): + Optional. The authorization URL to be used + for this flow. + refresh_url (str): + Optional. The URL to be used for obtaining + refresh tokens. + scopes (MutableMapping[str, str]): + The available scopes for the OAuth2 security + scheme. + """ + + authorization_url: str = proto.Field( + proto.STRING, + number=1, + ) + refresh_url: str = proto.Field( + proto.STRING, + number=2, + ) + scopes: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + + +class PasswordOAuthFlow(proto.Message): + r"""PasswordOAuthFlow defines a password OAuth flow. + + Attributes: + token_url (str): + Optional. The token URL to be used for this + flow. + refresh_url (str): + Optional. The URL to be used for obtaining + refresh tokens. + scopes (MutableMapping[str, str]): + The available scopes for the OAuth2 security + scheme. + """ + + token_url: str = proto.Field( + proto.STRING, + number=1, + ) + refresh_url: str = proto.Field( + proto.STRING, + number=2, + ) + scopes: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + + +class SendMessageRequest(proto.Message): + r"""Request message for SendMessage and SendStreamingMessage. + + Attributes: + message (google.cloud.geminidataanalytics_v1beta.types.A2AMessage): + Required. The message to send to the agent. + configuration (google.cloud.geminidataanalytics_v1beta.types.SendMessageConfiguration): + Optional. Configuration for the send request. + metadata (google.protobuf.struct_pb2.Struct): + Optional. Optional metadata for the request. + tenant (str): + Optional. Optional tenant, provided as a path + parameter. + """ + + message: "A2AMessage" = proto.Field( + proto.MESSAGE, + number=1, + message="A2AMessage", + ) + configuration: "SendMessageConfiguration" = proto.Field( + proto.MESSAGE, + number=2, + message="SendMessageConfiguration", + ) + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + tenant: str = proto.Field( + proto.STRING, + number=4, + ) + + +class GetAgentCardRequest(proto.Message): + r"""Request message for GetAgentCard. + + Attributes: + tenant (str): + Optional. Optional tenant, provided as a path + parameter. + """ + + tenant: str = proto.Field( + proto.STRING, + number=1, + ) + + +class SendMessageResponse(proto.Message): + r"""Response message for SendMessage. + + 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: + task (google.cloud.geminidataanalytics_v1beta.types.A2ATask): + Completed task. + + This field is a member of `oneof`_ ``payload``. + msg (google.cloud.geminidataanalytics_v1beta.types.A2AMessage): + Single message response. + + This field is a member of `oneof`_ ``payload``. + """ + + task: "A2ATask" = proto.Field( + proto.MESSAGE, + number=1, + oneof="payload", + message="A2ATask", + ) + msg: "A2AMessage" = proto.Field( + proto.MESSAGE, + number=2, + oneof="payload", + message="A2AMessage", + ) + + +class StreamResponse(proto.Message): + r"""The stream response for a message. + + 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: + task (google.cloud.geminidataanalytics_v1beta.types.A2ATask): + Completed task event. + + This field is a member of `oneof`_ ``payload``. + msg (google.cloud.geminidataanalytics_v1beta.types.A2AMessage): + Message event. + + This field is a member of `oneof`_ ``payload``. + status_update (google.cloud.geminidataanalytics_v1beta.types.TaskStatusUpdateEvent): + Task status update event. + + This field is a member of `oneof`_ ``payload``. + artifact_update (google.cloud.geminidataanalytics_v1beta.types.TaskArtifactUpdateEvent): + Task artifact update event. + + This field is a member of `oneof`_ ``payload``. + """ + + task: "A2ATask" = proto.Field( + proto.MESSAGE, + number=1, + oneof="payload", + message="A2ATask", + ) + msg: "A2AMessage" = proto.Field( + proto.MESSAGE, + number=2, + oneof="payload", + message="A2AMessage", + ) + status_update: "TaskStatusUpdateEvent" = proto.Field( + proto.MESSAGE, + number=3, + oneof="payload", + message="TaskStatusUpdateEvent", + ) + artifact_update: "TaskArtifactUpdateEvent" = proto.Field( + proto.MESSAGE, + number=4, + oneof="payload", + message="TaskArtifactUpdateEvent", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_agent.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_agent.py index e250674853cf..492f8cf03241 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_agent.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_agent.py @@ -23,6 +23,7 @@ from google.cloud.geminidataanalytics_v1beta.types import ( data_analytics_agent as gcg_data_analytics_agent, ) +from google.cloud.geminidataanalytics_v1beta.types import datasource __protobuf__ = proto.module( package="google.cloud.geminidataanalytics.v1beta", @@ -92,6 +93,67 @@ class DataAgent(proto.Message): ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. This field is a member of `oneof`_ ``_kms_key``. + bigquery_agent_analytics_enabled (bool): + Optional. Controls whether BigQuery Agent Analytics trace + logging is enabled for the agent. + + BigQuery Agent Analytics is in Preview and is delivered to + enrolled projects only. In a project that is not enrolled + this field is accepted and stored, but no trace rows are + written and no error is returned. + + Trace logging is additionally suppressed for the entire + turn, without error, when any table in the agent's + datasource carries row-level security, column-level security + or policy tags. It is also suppressed when that + determination cannot be made, for example when the caller + lacks permission to list a table's row access policies. + + Trace rows are written only when this is ``true`` and + ``bigquery_agent_analytics_table`` is set. On a BigQuery + agent, enabling this without a table has no effect: no table + is created for the agent and no rows are written. On an + agent whose datasource is not BigQuery, ``CreateDataAgent`` + rejects either field with ``INVALID_ARGUMENT``. + + This setting is independent of the project-level BigQuery + Agent Analytics setting configured through + ``SetAgentOpsObservability``. An agent does not inherit that + setting. + + This field is a member of `oneof`_ ``_bigquery_agent_analytics_enabled``. + bigquery_agent_analytics_table (google.cloud.geminidataanalytics_v1beta.types.BigQueryTableReference): + Optional. The BigQuery table that BigQuery Agent Analytics + trace rows are written to. Has no effect unless + ``bigquery_agent_analytics_enabled`` is ``true``. The + Preview enrollment described on that field applies here too. + + The trace table is validated when it is set on + ``CreateDataAgent``, or when it is included in the + ``update_mask`` of an ``UpdateDataAgent`` call. The + following are rejected with ``INVALID_ARGUMENT``: + + - The table must belong to the same project as the agent. + - The agent's datasource must be BigQuery. BigQuery Agent + Analytics is not supported for Looker, Looker Studio or + AlloyDB agents. + + These are validated against the agent as sent in the + request. An agent that carries no datasource is not + validated, and an agent switched to a non-BigQuery + datasource is not re-validated; in the latter case no trace + rows are written. + + The destination dataset must already exist and must grant + write access to the project's Gemini Data Analytics service + agent, whose address is + ``service-PROJECT_NUMBER@gcp-sa-geminidataanalytics.iam.gserviceaccount.com`` + (that grant is not performed on your behalf). Without it the + agent answers normally and no trace rows are written. + + Changing the table on an existing agent affects subsequent + turns only. Rows already written to the previous table are + left in place. """ data_analytics_agent: gcg_data_analytics_agent.DataAnalyticsAgent = proto.Field( @@ -142,6 +204,16 @@ class DataAgent(proto.Message): number=14, optional=True, ) + bigquery_agent_analytics_enabled: bool = proto.Field( + proto.BOOL, + number=18, + optional=True, + ) + bigquery_agent_analytics_table: datasource.BigQueryTableReference = proto.Field( + proto.MESSAGE, + number=19, + message=datasource.BigQueryTableReference, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_agent_service.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_agent_service.py index 610f1a76deb5..ad83e960f96c 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_agent_service.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_agent_service.py @@ -35,6 +35,11 @@ "UpdateDataAgentRequest", "DeleteDataAgentRequest", "OperationMetadata", + "SetAgentOpsObservabilityRequest", + "SetAgentOpsObservabilityResponse", + "SetAgentOpsObservabilityMetadata", + "RetrieveAgentOpsObservabilityRequest", + "RetrieveAgentOpsObservabilityResponse", }, ) @@ -68,6 +73,9 @@ class ListDataAgentsRequest(proto.Message): Optional. If true, the list results will include soft-deleted DataAgents. Defaults to false. + creator_filter (google.cloud.geminidataanalytics_v1beta.types.ListAccessibleDataAgentsRequest.CreatorFilter): + Optional. Filter for the creator of the + agent. """ parent: str = proto.Field( @@ -94,6 +102,11 @@ class ListDataAgentsRequest(proto.Message): proto.BOOL, number=6, ) + creator_filter: "ListAccessibleDataAgentsRequest.CreatorFilter" = proto.Field( + proto.ENUM, + number=8, + enum="ListAccessibleDataAgentsRequest.CreatorFilter", + ) class ListDataAgentsResponse(proto.Message): @@ -469,4 +482,159 @@ class OperationMetadata(proto.Message): ) +class SetAgentOpsObservabilityRequest(proto.Message): + r"""Request for SetAgentOpsObservability. + + Attributes: + parent (str): + Required. Parent value for + SetAgentOpsObservabilityRequest. Format: + projects/{project}/locations/{location} + telemetry_enabled (bool): + Optional. Whether to enable or disable AgentOps + observability. When update_mask is provided, this field is + ignored unless specified in the mask. + data_source_type (str): + Required. The data source type for which to + set observability settings. Examples: + "bigquery", "looker". + bqaa_enabled (bool): + Optional. Whether BigQuery Agent Analytics is enabled. Note: + An explicit ``update_mask`` containing "bqaa_enabled" is + required to modify this field. If ``update_mask`` is + omitted, this field is ignored and an existing enabled + setting cannot be disabled. + + This is a project-level setting and does not by itself + enable trace logging for any individual agent. Per-agent + trace logging is controlled by + ``DataAgent.bigquery_agent_analytics_enabled`` together with + ``DataAgent.bigquery_agent_analytics_table``; an agent does + not inherit this setting. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten by the update. The fields specified in the + update_mask are relative to the resource. A field will be + overwritten if it is in the mask. + + If the user does not provide a mask, only + ``telemetry_enabled`` will be updated (for backward + compatibility with legacy callers). Note that disabling + BigQuery Agent Analytics (``bqaa_enabled = false``) requires + providing an explicit ``update_mask`` containing + "bqaa_enabled". + + Per AIP-161: + + - The special wildcard value '\*' is supported to update all + fields. + - Field paths should use snake_case, though camelCase + equivalents (``telemetryEnabled``, ``bqaaEnabled``) are + accepted for REST/JSON transcoding compatibility. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + telemetry_enabled: bool = proto.Field( + proto.BOOL, + number=2, + ) + data_source_type: str = proto.Field( + proto.STRING, + number=3, + ) + bqaa_enabled: bool = proto.Field( + proto.BOOL, + number=4, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + + +class SetAgentOpsObservabilityResponse(proto.Message): + r"""Response for SetAgentOpsObservability.""" + + +class SetAgentOpsObservabilityMetadata(proto.Message): + r"""Metadata for SetAgentOpsObservability.""" + + +class RetrieveAgentOpsObservabilityRequest(proto.Message): + r"""Request for RetrieveAgentOpsObservability. + + Attributes: + parent (str): + Required. Parent value for + RetrieveAgentOpsObservabilityRequest. Format: + projects/{project}/locations/{location} + data_source_type (str): + Required. The data source type for which to + retrieve observability settings. Examples: + "bigquery", "looker". + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + data_source_type: str = proto.Field( + proto.STRING, + number=2, + ) + + +class RetrieveAgentOpsObservabilityResponse(proto.Message): + r"""Response for RetrieveAgentOpsObservability. + + Attributes: + telemetry_enabled (bool): + Output only. Whether AgentOps observability + telemetry is enabled. + bigquery_enabled (bool): + Output only. Whether BigQuery API is enabled. + cloud_trace_enabled (bool): + Output only. Whether Cloud Trace API is + enabled. + cloud_monitoring_enabled (bool): + Output only. Whether Cloud Monitoring API is + enabled. + cloud_logging_enabled (bool): + Output only. Whether Cloud Logging API is + enabled. + bqaa_enabled (bool): + Output only. Whether BigQuery Agent Analytics + is enabled. + """ + + telemetry_enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + bigquery_enabled: bool = proto.Field( + proto.BOOL, + number=3, + ) + cloud_trace_enabled: bool = proto.Field( + proto.BOOL, + number=4, + ) + cloud_monitoring_enabled: bool = proto.Field( + proto.BOOL, + number=5, + ) + cloud_logging_enabled: bool = proto.Field( + proto.BOOL, + number=6, + ) + bqaa_enabled: bool = proto.Field( + proto.BOOL, + number=7, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_chat_service.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_chat_service.py index e166aec75a64..992e202c201f 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_chat_service.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_chat_service.py @@ -23,7 +23,7 @@ from google.cloud.geminidataanalytics_v1beta.types import context as gcg_context from google.cloud.geminidataanalytics_v1beta.types import credentials as gcg_credentials -from google.cloud.geminidataanalytics_v1beta.types import datasource +from google.cloud.geminidataanalytics_v1beta.types import datasource, usage __protobuf__ = proto.module( package="google.cloud.geminidataanalytics.v1beta", @@ -254,6 +254,8 @@ class QueryDataResponse(proto.Message): and may change at any time without notice. Do not write production code or business logic depending on the fields in this object. + token_usage (google.cloud.geminidataanalytics_v1beta.types.TokenUsage): + Overall token usage for the request. """ generated_query: str = proto.Field( @@ -282,6 +284,11 @@ class QueryDataResponse(proto.Message): number=9, message=struct_pb2.Struct, ) + token_usage: usage.TokenUsage = proto.Field( + proto.MESSAGE, + number=10, + message=usage.TokenUsage, + ) class ExecutedQueryResult(proto.Message): @@ -296,13 +303,11 @@ class ExecutedQueryResult(proto.Message): total_row_count (int): The total number of rows in the full result set, if known. This may be an estimate or an - exact count. - - Note: if an internal limit (such as LIMIT 1000) - was applied during query execution to guard - against excessive data transfer, this count - reflects the truncated result size rather than - the unrestricted table result size. + exact count. Note: if an internal limit (such as + LIMIT 1000) was applied during query execution + to guard against excessive data transfer, this + count reflects the truncated result size rather + than the unrestricted table result size. partial_result (bool): Set to true if the returned rows in ``query_result`` are a subset of the full result. This can happen, for example, if @@ -559,7 +564,8 @@ class ThinkingMode(proto.Enum): Values: THINKING_MODE_UNSPECIFIED (0): Unspecified thinking mode, agent will use - THINKING mode by default. + THINKING mode by default except for BigQuery + user defaulting to FAST mode by default. FAST (1): Fast mode, answers quickly. THINKING (2): @@ -571,12 +577,12 @@ class ThinkingMode(proto.Enum): THINKING = 2 class Model(proto.Enum): - r"""Model selection for the agent. + r"""Model selection for the agent for BigQuery users. Values: MODEL_UNSPECIFIED (0): - No model specified. The default model will be - used. + No model specified. Either preview or non + preview model can be used. LATEST_GA_MODEL (1): Use the most up-to-date non-preview model. This may constrain certain request level diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/datasource.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/datasource.py index 5b568af63ce7..71337eb498ad 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/datasource.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/datasource.py @@ -180,11 +180,12 @@ class BigQueryTableReferences(proto.Message): table_references (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.BigQueryTableReference]): Optional. References to BigQuery tables. property_graph_references (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.BigQueryPropertyGraphReference]): - Optional. Preview feature. References to - BigQuery property graphs. Note: Data sources - must exclusively use either tables or property - graphs, not both. When using property graphs, a - maximum of one graph reference is supported. + Optional. References to BigQuery graphs. + + Note: "property graph" is the former name for + BigQuery Graph. The field and message names + retain the original term for backward + compatibility; both refer to the same resource. agent_context_reference (google.cloud.geminidataanalytics_v1beta.types.AgentContextReference): Optional. Parameters for retrieving data from Agent Context. diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/usage.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/usage.py new file mode 100644 index 000000000000..c283f1bfd4bb --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/usage.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.geminidataanalytics.v1beta", + manifest={ + "TokenUsage", + }, +) + + +class TokenUsage(proto.Message): + r"""Overall token usage tracking for the response. + + Attributes: + input_token_count (int): + The total number of input tokens used in this + request. + output_token_count (int): + The total number of output tokens used in + this request. + """ + + input_token_count: int = proto.Field( + proto.INT32, + number=1, + ) + output_token_count: int = proto.Field( + proto.INT32, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_agent_service_retrieve_agent_ops_observability_async.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_agent_service_retrieve_agent_ops_observability_async.py new file mode 100644 index 000000000000..89de4c515780 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_agent_service_retrieve_agent_ops_observability_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RetrieveAgentOpsObservability +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1_generated_DataAgentService_RetrieveAgentOpsObservability_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1 + + +async def sample_retrieve_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1.DataAgentServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1.RetrieveAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + response = await client.retrieve_agent_ops_observability(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1_generated_DataAgentService_RetrieveAgentOpsObservability_async] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_agent_service_retrieve_agent_ops_observability_sync.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_agent_service_retrieve_agent_ops_observability_sync.py new file mode 100644 index 000000000000..6e743fa16d24 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_agent_service_retrieve_agent_ops_observability_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RetrieveAgentOpsObservability +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1_generated_DataAgentService_RetrieveAgentOpsObservability_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1 + + +def sample_retrieve_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1.DataAgentServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1.RetrieveAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + response = client.retrieve_agent_ops_observability(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1_generated_DataAgentService_RetrieveAgentOpsObservability_sync] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_agent_service_set_agent_ops_observability_async.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_agent_service_set_agent_ops_observability_async.py new file mode 100644 index 000000000000..28d990b15edb --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_agent_service_set_agent_ops_observability_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetAgentOpsObservability +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1_generated_DataAgentService_SetAgentOpsObservability_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1 + + +async def sample_set_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1.DataAgentServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1.SetAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + operation = await client.set_agent_ops_observability(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1_generated_DataAgentService_SetAgentOpsObservability_async] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_agent_service_set_agent_ops_observability_sync.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_agent_service_set_agent_ops_observability_sync.py new file mode 100644 index 000000000000..026c900fc35f --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_agent_service_set_agent_ops_observability_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetAgentOpsObservability +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1_generated_DataAgentService_SetAgentOpsObservability_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1 + + +def sample_set_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1.DataAgentServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1.SetAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + operation = client.set_agent_ops_observability(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1_generated_DataAgentService_SetAgentOpsObservability_sync] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_chat_service_update_conversation_async.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_chat_service_update_conversation_async.py new file mode 100644 index 000000000000..5db4a0d646a5 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_chat_service_update_conversation_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1_generated_DataChatService_UpdateConversation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1 + + +async def sample_update_conversation(): + # Create a client + client = geminidataanalytics_v1.DataChatServiceAsyncClient() + + # Initialize request argument(s) + conversation = geminidataanalytics_v1.Conversation() + conversation.agents = ["agents_value1", "agents_value2"] + + request = geminidataanalytics_v1.UpdateConversationRequest( + conversation=conversation, + ) + + # Make the request + response = await client.update_conversation(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1_generated_DataChatService_UpdateConversation_async] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_chat_service_update_conversation_sync.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_chat_service_update_conversation_sync.py new file mode 100644 index 000000000000..c1d07b5257b3 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1_generated_data_chat_service_update_conversation_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1_generated_DataChatService_UpdateConversation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1 + + +def sample_update_conversation(): + # Create a client + client = geminidataanalytics_v1.DataChatServiceClient() + + # Initialize request argument(s) + conversation = geminidataanalytics_v1.Conversation() + conversation.agents = ["agents_value1", "agents_value2"] + + request = geminidataanalytics_v1.UpdateConversationRequest( + conversation=conversation, + ) + + # Make the request + response = client.update_conversation(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1_generated_DataChatService_UpdateConversation_sync] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_get_agent_card_async.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_get_agent_card_async.py new file mode 100644 index 000000000000..4b868ed52186 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_get_agent_card_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAgentCard +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1alpha_generated_DataA2AService_GetAgentCard_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1alpha + + +async def sample_get_agent_card(): + # Create a client + client = geminidataanalytics_v1alpha.DataA2AServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.GetAgentCardRequest() + + # Make the request + response = await client.get_agent_card(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1alpha_generated_DataA2AService_GetAgentCard_async] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_get_agent_card_sync.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_get_agent_card_sync.py new file mode 100644 index 000000000000..9bf59df3e2e5 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_get_agent_card_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAgentCard +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1alpha_generated_DataA2AService_GetAgentCard_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1alpha + + +def sample_get_agent_card(): + # Create a client + client = geminidataanalytics_v1alpha.DataA2AServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.GetAgentCardRequest() + + # Make the request + response = client.get_agent_card(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1alpha_generated_DataA2AService_GetAgentCard_sync] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_send_message_async.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_send_message_async.py new file mode 100644 index 000000000000..6adbf4693403 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_send_message_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SendMessage +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1alpha_generated_DataA2AService_SendMessage_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1alpha + + +async def sample_send_message(): + # Create a client + client = geminidataanalytics_v1alpha.DataA2AServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.SendMessageRequest() + + # Make the request + response = await client.send_message(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1alpha_generated_DataA2AService_SendMessage_async] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_send_message_sync.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_send_message_sync.py new file mode 100644 index 000000000000..0c44260e3b31 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_send_message_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SendMessage +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1alpha_generated_DataA2AService_SendMessage_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1alpha + + +def sample_send_message(): + # Create a client + client = geminidataanalytics_v1alpha.DataA2AServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.SendMessageRequest() + + # Make the request + response = client.send_message(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1alpha_generated_DataA2AService_SendMessage_sync] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_send_streaming_message_async.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_send_streaming_message_async.py new file mode 100644 index 000000000000..ef6727ca29d8 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_send_streaming_message_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SendStreamingMessage +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1alpha_generated_DataA2AService_SendStreamingMessage_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1alpha + + +async def sample_send_streaming_message(): + # Create a client + client = geminidataanalytics_v1alpha.DataA2AServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.SendMessageRequest() + + # Make the request + stream = await client.send_streaming_message(request=request) + + # Handle the response + async for response in stream: + print(response) + + +# [END geminidataanalytics_v1alpha_generated_DataA2AService_SendStreamingMessage_async] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_send_streaming_message_sync.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_send_streaming_message_sync.py new file mode 100644 index 000000000000..135df1dedb9e --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_a2a_service_send_streaming_message_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SendStreamingMessage +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1alpha_generated_DataA2AService_SendStreamingMessage_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1alpha + + +def sample_send_streaming_message(): + # Create a client + client = geminidataanalytics_v1alpha.DataA2AServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.SendMessageRequest() + + # Make the request + stream = client.send_streaming_message(request=request) + + # Handle the response + for response in stream: + print(response) + + +# [END geminidataanalytics_v1alpha_generated_DataA2AService_SendStreamingMessage_sync] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_agent_service_retrieve_agent_ops_observability_async.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_agent_service_retrieve_agent_ops_observability_async.py new file mode 100644 index 000000000000..c68abeafd83f --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_agent_service_retrieve_agent_ops_observability_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RetrieveAgentOpsObservability +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1alpha_generated_DataAgentService_RetrieveAgentOpsObservability_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1alpha + + +async def sample_retrieve_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1alpha.DataAgentServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.RetrieveAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + response = await client.retrieve_agent_ops_observability(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1alpha_generated_DataAgentService_RetrieveAgentOpsObservability_async] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_agent_service_retrieve_agent_ops_observability_sync.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_agent_service_retrieve_agent_ops_observability_sync.py new file mode 100644 index 000000000000..09b2e79af081 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_agent_service_retrieve_agent_ops_observability_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RetrieveAgentOpsObservability +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1alpha_generated_DataAgentService_RetrieveAgentOpsObservability_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1alpha + + +def sample_retrieve_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1alpha.DataAgentServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.RetrieveAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + response = client.retrieve_agent_ops_observability(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1alpha_generated_DataAgentService_RetrieveAgentOpsObservability_sync] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_agent_service_set_agent_ops_observability_async.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_agent_service_set_agent_ops_observability_async.py new file mode 100644 index 000000000000..4568e824eca6 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_agent_service_set_agent_ops_observability_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetAgentOpsObservability +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1alpha_generated_DataAgentService_SetAgentOpsObservability_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1alpha + + +async def sample_set_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1alpha.DataAgentServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.SetAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + operation = await client.set_agent_ops_observability(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1alpha_generated_DataAgentService_SetAgentOpsObservability_async] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_agent_service_set_agent_ops_observability_sync.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_agent_service_set_agent_ops_observability_sync.py new file mode 100644 index 000000000000..d625406dccb6 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_agent_service_set_agent_ops_observability_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetAgentOpsObservability +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1alpha_generated_DataAgentService_SetAgentOpsObservability_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1alpha + + +def sample_set_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1alpha.DataAgentServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1alpha.SetAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + operation = client.set_agent_ops_observability(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1alpha_generated_DataAgentService_SetAgentOpsObservability_sync] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_update_conversation_async.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_update_conversation_async.py new file mode 100644 index 000000000000..90d7a8c598b9 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_update_conversation_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1alpha_generated_DataChatService_UpdateConversation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1alpha + + +async def sample_update_conversation(): + # Create a client + client = geminidataanalytics_v1alpha.DataChatServiceAsyncClient() + + # Initialize request argument(s) + conversation = geminidataanalytics_v1alpha.Conversation() + conversation.agents = ["agents_value1", "agents_value2"] + + request = geminidataanalytics_v1alpha.UpdateConversationRequest( + conversation=conversation, + ) + + # Make the request + response = await client.update_conversation(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1alpha_generated_DataChatService_UpdateConversation_async] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_update_conversation_sync.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_update_conversation_sync.py new file mode 100644 index 000000000000..1b09dd1285c3 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_update_conversation_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1alpha_generated_DataChatService_UpdateConversation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1alpha + + +def sample_update_conversation(): + # Create a client + client = geminidataanalytics_v1alpha.DataChatServiceClient() + + # Initialize request argument(s) + conversation = geminidataanalytics_v1alpha.Conversation() + conversation.agents = ["agents_value1", "agents_value2"] + + request = geminidataanalytics_v1alpha.UpdateConversationRequest( + conversation=conversation, + ) + + # Make the request + response = client.update_conversation(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1alpha_generated_DataChatService_UpdateConversation_sync] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_get_agent_card_async.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_get_agent_card_async.py new file mode 100644 index 000000000000..651df2e31c1c --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_get_agent_card_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAgentCard +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1beta_generated_DataA2AService_GetAgentCard_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1beta + + +async def sample_get_agent_card(): + # Create a client + client = geminidataanalytics_v1beta.DataA2AServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.GetAgentCardRequest() + + # Make the request + response = await client.get_agent_card(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1beta_generated_DataA2AService_GetAgentCard_async] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_get_agent_card_sync.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_get_agent_card_sync.py new file mode 100644 index 000000000000..7a9c88709f25 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_get_agent_card_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAgentCard +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1beta_generated_DataA2AService_GetAgentCard_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1beta + + +def sample_get_agent_card(): + # Create a client + client = geminidataanalytics_v1beta.DataA2AServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.GetAgentCardRequest() + + # Make the request + response = client.get_agent_card(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1beta_generated_DataA2AService_GetAgentCard_sync] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_send_message_async.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_send_message_async.py new file mode 100644 index 000000000000..fafa7c73543d --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_send_message_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SendMessage +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1beta_generated_DataA2AService_SendMessage_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1beta + + +async def sample_send_message(): + # Create a client + client = geminidataanalytics_v1beta.DataA2AServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.SendMessageRequest() + + # Make the request + response = await client.send_message(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1beta_generated_DataA2AService_SendMessage_async] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_send_message_sync.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_send_message_sync.py new file mode 100644 index 000000000000..828efaf9da27 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_send_message_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SendMessage +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1beta_generated_DataA2AService_SendMessage_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1beta + + +def sample_send_message(): + # Create a client + client = geminidataanalytics_v1beta.DataA2AServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.SendMessageRequest() + + # Make the request + response = client.send_message(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1beta_generated_DataA2AService_SendMessage_sync] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_send_streaming_message_async.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_send_streaming_message_async.py new file mode 100644 index 000000000000..7a2588346a51 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_send_streaming_message_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SendStreamingMessage +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1beta_generated_DataA2AService_SendStreamingMessage_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1beta + + +async def sample_send_streaming_message(): + # Create a client + client = geminidataanalytics_v1beta.DataA2AServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.SendMessageRequest() + + # Make the request + stream = await client.send_streaming_message(request=request) + + # Handle the response + async for response in stream: + print(response) + + +# [END geminidataanalytics_v1beta_generated_DataA2AService_SendStreamingMessage_async] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_send_streaming_message_sync.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_send_streaming_message_sync.py new file mode 100644 index 000000000000..7382167aa31b --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_a2a_service_send_streaming_message_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SendStreamingMessage +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1beta_generated_DataA2AService_SendStreamingMessage_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1beta + + +def sample_send_streaming_message(): + # Create a client + client = geminidataanalytics_v1beta.DataA2AServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.SendMessageRequest() + + # Make the request + stream = client.send_streaming_message(request=request) + + # Handle the response + for response in stream: + print(response) + + +# [END geminidataanalytics_v1beta_generated_DataA2AService_SendStreamingMessage_sync] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_agent_service_retrieve_agent_ops_observability_async.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_agent_service_retrieve_agent_ops_observability_async.py new file mode 100644 index 000000000000..aa31f52126d1 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_agent_service_retrieve_agent_ops_observability_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RetrieveAgentOpsObservability +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1beta_generated_DataAgentService_RetrieveAgentOpsObservability_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1beta + + +async def sample_retrieve_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1beta.DataAgentServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.RetrieveAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + response = await client.retrieve_agent_ops_observability(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1beta_generated_DataAgentService_RetrieveAgentOpsObservability_async] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_agent_service_retrieve_agent_ops_observability_sync.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_agent_service_retrieve_agent_ops_observability_sync.py new file mode 100644 index 000000000000..82f93647fa38 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_agent_service_retrieve_agent_ops_observability_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RetrieveAgentOpsObservability +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1beta_generated_DataAgentService_RetrieveAgentOpsObservability_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1beta + + +def sample_retrieve_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1beta.DataAgentServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.RetrieveAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + response = client.retrieve_agent_ops_observability(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1beta_generated_DataAgentService_RetrieveAgentOpsObservability_sync] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_agent_service_set_agent_ops_observability_async.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_agent_service_set_agent_ops_observability_async.py new file mode 100644 index 000000000000..f30af1a93e9f --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_agent_service_set_agent_ops_observability_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetAgentOpsObservability +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1beta_generated_DataAgentService_SetAgentOpsObservability_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1beta + + +async def sample_set_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1beta.DataAgentServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.SetAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + operation = await client.set_agent_ops_observability(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1beta_generated_DataAgentService_SetAgentOpsObservability_async] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_agent_service_set_agent_ops_observability_sync.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_agent_service_set_agent_ops_observability_sync.py new file mode 100644 index 000000000000..4fd8e425df63 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_agent_service_set_agent_ops_observability_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetAgentOpsObservability +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1beta_generated_DataAgentService_SetAgentOpsObservability_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1beta + + +def sample_set_agent_ops_observability(): + # Create a client + client = geminidataanalytics_v1beta.DataAgentServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.SetAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Make the request + operation = client.set_agent_ops_observability(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1beta_generated_DataAgentService_SetAgentOpsObservability_sync] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_update_conversation_async.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_update_conversation_async.py new file mode 100644 index 000000000000..94e20213540b --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_update_conversation_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1beta_generated_DataChatService_UpdateConversation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1beta + + +async def sample_update_conversation(): + # Create a client + client = geminidataanalytics_v1beta.DataChatServiceAsyncClient() + + # Initialize request argument(s) + conversation = geminidataanalytics_v1beta.Conversation() + conversation.agents = ["agents_value1", "agents_value2"] + + request = geminidataanalytics_v1beta.UpdateConversationRequest( + conversation=conversation, + ) + + # Make the request + response = await client.update_conversation(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1beta_generated_DataChatService_UpdateConversation_async] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_update_conversation_sync.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_update_conversation_sync.py new file mode 100644 index 000000000000..3d0bc37f652d --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_update_conversation_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-geminidataanalytics + + +# [START geminidataanalytics_v1beta_generated_DataChatService_UpdateConversation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import geminidataanalytics_v1beta + + +def sample_update_conversation(): + # Create a client + client = geminidataanalytics_v1beta.DataChatServiceClient() + + # Initialize request argument(s) + conversation = geminidataanalytics_v1beta.Conversation() + conversation.agents = ["agents_value1", "agents_value2"] + + request = geminidataanalytics_v1beta.UpdateConversationRequest( + conversation=conversation, + ) + + # Make the request + response = client.update_conversation(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1beta_generated_DataChatService_UpdateConversation_sync] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1.json b/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1.json index 62f0b2251d41..87fc7c55cbd5 100644 --- a/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1.json +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1.json @@ -1325,6 +1325,352 @@ ], "title": "geminidataanalytics_v1_generated_data_agent_service_list_data_agents_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.geminidataanalytics_v1.DataAgentServiceAsyncClient", + "shortName": "DataAgentServiceAsyncClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1.DataAgentServiceAsyncClient.retrieve_agent_ops_observability", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1.DataAgentService.RetrieveAgentOpsObservability", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1.DataAgentService", + "shortName": "DataAgentService" + }, + "shortName": "RetrieveAgentOpsObservability" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1.types.RetrieveAgentOpsObservabilityRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "data_source_type", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1.types.RetrieveAgentOpsObservabilityResponse", + "shortName": "retrieve_agent_ops_observability" + }, + "description": "Sample for RetrieveAgentOpsObservability", + "file": "geminidataanalytics_v1_generated_data_agent_service_retrieve_agent_ops_observability_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1_generated_DataAgentService_RetrieveAgentOpsObservability_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1_generated_data_agent_service_retrieve_agent_ops_observability_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.geminidataanalytics_v1.DataAgentServiceClient", + "shortName": "DataAgentServiceClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1.DataAgentServiceClient.retrieve_agent_ops_observability", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1.DataAgentService.RetrieveAgentOpsObservability", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1.DataAgentService", + "shortName": "DataAgentService" + }, + "shortName": "RetrieveAgentOpsObservability" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1.types.RetrieveAgentOpsObservabilityRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "data_source_type", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1.types.RetrieveAgentOpsObservabilityResponse", + "shortName": "retrieve_agent_ops_observability" + }, + "description": "Sample for RetrieveAgentOpsObservability", + "file": "geminidataanalytics_v1_generated_data_agent_service_retrieve_agent_ops_observability_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1_generated_DataAgentService_RetrieveAgentOpsObservability_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1_generated_data_agent_service_retrieve_agent_ops_observability_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.geminidataanalytics_v1.DataAgentServiceAsyncClient", + "shortName": "DataAgentServiceAsyncClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1.DataAgentServiceAsyncClient.set_agent_ops_observability", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1.DataAgentService.SetAgentOpsObservability", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1.DataAgentService", + "shortName": "DataAgentService" + }, + "shortName": "SetAgentOpsObservability" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1.types.SetAgentOpsObservabilityRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "telemetry_enabled", + "type": "bool" + }, + { + "name": "data_source_type", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "set_agent_ops_observability" + }, + "description": "Sample for SetAgentOpsObservability", + "file": "geminidataanalytics_v1_generated_data_agent_service_set_agent_ops_observability_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1_generated_DataAgentService_SetAgentOpsObservability_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": "geminidataanalytics_v1_generated_data_agent_service_set_agent_ops_observability_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.geminidataanalytics_v1.DataAgentServiceClient", + "shortName": "DataAgentServiceClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1.DataAgentServiceClient.set_agent_ops_observability", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1.DataAgentService.SetAgentOpsObservability", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1.DataAgentService", + "shortName": "DataAgentService" + }, + "shortName": "SetAgentOpsObservability" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1.types.SetAgentOpsObservabilityRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "telemetry_enabled", + "type": "bool" + }, + { + "name": "data_source_type", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "set_agent_ops_observability" + }, + "description": "Sample for SetAgentOpsObservability", + "file": "geminidataanalytics_v1_generated_data_agent_service_set_agent_ops_observability_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1_generated_DataAgentService_SetAgentOpsObservability_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": "geminidataanalytics_v1_generated_data_agent_service_set_agent_ops_observability_sync.py" + }, { "canonical": true, "clientMethod": { @@ -2791,6 +3137,175 @@ } ], "title": "geminidataanalytics_v1_generated_data_chat_service_list_messages_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.geminidataanalytics_v1.DataChatServiceAsyncClient", + "shortName": "DataChatServiceAsyncClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1.DataChatServiceAsyncClient.update_conversation", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1.DataChatService.UpdateConversation", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1.DataChatService", + "shortName": "DataChatService" + }, + "shortName": "UpdateConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1.types.UpdateConversationRequest" + }, + { + "name": "conversation", + "type": "google.cloud.geminidataanalytics_v1.types.Conversation" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1.types.Conversation", + "shortName": "update_conversation" + }, + "description": "Sample for UpdateConversation", + "file": "geminidataanalytics_v1_generated_data_chat_service_update_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1_generated_DataChatService_UpdateConversation_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1_generated_data_chat_service_update_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.geminidataanalytics_v1.DataChatServiceClient", + "shortName": "DataChatServiceClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1.DataChatServiceClient.update_conversation", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1.DataChatService.UpdateConversation", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1.DataChatService", + "shortName": "DataChatService" + }, + "shortName": "UpdateConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1.types.UpdateConversationRequest" + }, + { + "name": "conversation", + "type": "google.cloud.geminidataanalytics_v1.types.Conversation" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1.types.Conversation", + "shortName": "update_conversation" + }, + "description": "Sample for UpdateConversation", + "file": "geminidataanalytics_v1_generated_data_chat_service_update_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1_generated_DataChatService_UpdateConversation_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1_generated_data_chat_service_update_conversation_sync.py" } ] } diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1alpha.json b/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1alpha.json index 475e3bc9e97f..7c46e8214633 100644 --- a/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1alpha.json +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1alpha.json @@ -11,6 +11,505 @@ "version": "0.13.3" }, "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataA2AServiceAsyncClient", + "shortName": "DataA2AServiceAsyncClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataA2AServiceAsyncClient.get_agent_card", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService.GetAgentCard", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "shortName": "DataA2AService" + }, + "shortName": "GetAgentCard" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1alpha.types.GetAgentCardRequest" + }, + { + "name": "tenant", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1alpha.types.AgentCard", + "shortName": "get_agent_card" + }, + "description": "Sample for GetAgentCard", + "file": "geminidataanalytics_v1alpha_generated_data_a2a_service_get_agent_card_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1alpha_generated_DataA2AService_GetAgentCard_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1alpha_generated_data_a2a_service_get_agent_card_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataA2AServiceClient", + "shortName": "DataA2AServiceClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataA2AServiceClient.get_agent_card", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService.GetAgentCard", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "shortName": "DataA2AService" + }, + "shortName": "GetAgentCard" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1alpha.types.GetAgentCardRequest" + }, + { + "name": "tenant", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1alpha.types.AgentCard", + "shortName": "get_agent_card" + }, + "description": "Sample for GetAgentCard", + "file": "geminidataanalytics_v1alpha_generated_data_a2a_service_get_agent_card_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1alpha_generated_DataA2AService_GetAgentCard_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1alpha_generated_data_a2a_service_get_agent_card_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataA2AServiceAsyncClient", + "shortName": "DataA2AServiceAsyncClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataA2AServiceAsyncClient.send_message", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService.SendMessage", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "shortName": "DataA2AService" + }, + "shortName": "SendMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1alpha.types.SendMessageRequest" + }, + { + "name": "tenant", + "type": "str" + }, + { + "name": "message", + "type": "google.cloud.geminidataanalytics_v1alpha.types.A2AMessage" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1alpha.types.SendMessageResponse", + "shortName": "send_message" + }, + "description": "Sample for SendMessage", + "file": "geminidataanalytics_v1alpha_generated_data_a2a_service_send_message_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1alpha_generated_DataA2AService_SendMessage_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1alpha_generated_data_a2a_service_send_message_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataA2AServiceClient", + "shortName": "DataA2AServiceClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataA2AServiceClient.send_message", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService.SendMessage", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "shortName": "DataA2AService" + }, + "shortName": "SendMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1alpha.types.SendMessageRequest" + }, + { + "name": "tenant", + "type": "str" + }, + { + "name": "message", + "type": "google.cloud.geminidataanalytics_v1alpha.types.A2AMessage" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1alpha.types.SendMessageResponse", + "shortName": "send_message" + }, + "description": "Sample for SendMessage", + "file": "geminidataanalytics_v1alpha_generated_data_a2a_service_send_message_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1alpha_generated_DataA2AService_SendMessage_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1alpha_generated_data_a2a_service_send_message_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataA2AServiceAsyncClient", + "shortName": "DataA2AServiceAsyncClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataA2AServiceAsyncClient.send_streaming_message", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService.SendStreamingMessage", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "shortName": "DataA2AService" + }, + "shortName": "SendStreamingMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1alpha.types.SendMessageRequest" + }, + { + "name": "tenant", + "type": "str" + }, + { + "name": "message", + "type": "google.cloud.geminidataanalytics_v1alpha.types.A2AMessage" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.cloud.geminidataanalytics_v1alpha.types.StreamResponse]", + "shortName": "send_streaming_message" + }, + "description": "Sample for SendStreamingMessage", + "file": "geminidataanalytics_v1alpha_generated_data_a2a_service_send_streaming_message_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1alpha_generated_DataA2AService_SendStreamingMessage_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1alpha_generated_data_a2a_service_send_streaming_message_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataA2AServiceClient", + "shortName": "DataA2AServiceClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataA2AServiceClient.send_streaming_message", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService.SendStreamingMessage", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataA2AService", + "shortName": "DataA2AService" + }, + "shortName": "SendStreamingMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1alpha.types.SendMessageRequest" + }, + { + "name": "tenant", + "type": "str" + }, + { + "name": "message", + "type": "google.cloud.geminidataanalytics_v1alpha.types.A2AMessage" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.cloud.geminidataanalytics_v1alpha.types.StreamResponse]", + "shortName": "send_streaming_message" + }, + "description": "Sample for SendStreamingMessage", + "file": "geminidataanalytics_v1alpha_generated_data_a2a_service_send_streaming_message_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1alpha_generated_DataA2AService_SendStreamingMessage_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1alpha_generated_data_a2a_service_send_streaming_message_sync.py" + }, { "canonical": true, "clientMethod": { @@ -58,22 +557,199 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.geminidataanalytics_v1alpha.types.DataAgent", - "shortName": "create_data_agent_sync" + "resultType": "google.cloud.geminidataanalytics_v1alpha.types.DataAgent", + "shortName": "create_data_agent_sync" + }, + "description": "Sample for CreateDataAgentSync", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_create_data_agent_sync_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_CreateDataAgentSync_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": "geminidataanalytics_v1alpha_generated_data_agent_service_create_data_agent_sync_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient", + "shortName": "DataAgentServiceClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.create_data_agent_sync", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.CreateDataAgentSync", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", + "shortName": "DataAgentService" + }, + "shortName": "CreateDataAgentSync" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1alpha.types.CreateDataAgentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "data_agent", + "type": "google.cloud.geminidataanalytics_v1alpha.types.DataAgent" + }, + { + "name": "data_agent_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1alpha.types.DataAgent", + "shortName": "create_data_agent_sync" + }, + "description": "Sample for CreateDataAgentSync", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_create_data_agent_sync_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_CreateDataAgentSync_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": "geminidataanalytics_v1alpha_generated_data_agent_service_create_data_agent_sync_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient", + "shortName": "DataAgentServiceAsyncClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient.create_data_agent", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.CreateDataAgent", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", + "shortName": "DataAgentService" + }, + "shortName": "CreateDataAgent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1alpha.types.CreateDataAgentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "data_agent", + "type": "google.cloud.geminidataanalytics_v1alpha.types.DataAgent" + }, + { + "name": "data_agent_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_data_agent" }, - "description": "Sample for CreateDataAgentSync", - "file": "geminidataanalytics_v1alpha_generated_data_agent_service_create_data_agent_sync_async.py", + "description": "Sample for CreateDataAgent", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_create_data_agent_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_CreateDataAgentSync_async", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_CreateDataAgent_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -88,17 +764,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1alpha_generated_data_agent_service_create_data_agent_sync_async.py" + "title": "geminidataanalytics_v1alpha_generated_data_agent_service_create_data_agent_async.py" }, { "canonical": true, @@ -107,14 +783,14 @@ "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient", "shortName": "DataAgentServiceClient" }, - "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.create_data_agent_sync", + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.create_data_agent", "method": { - "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.CreateDataAgentSync", + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.CreateDataAgent", "service": { "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "CreateDataAgentSync" + "shortName": "CreateDataAgent" }, "parameters": [ { @@ -146,22 +822,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.geminidataanalytics_v1alpha.types.DataAgent", - "shortName": "create_data_agent_sync" + "resultType": "google.api_core.operation.Operation", + "shortName": "create_data_agent" }, - "description": "Sample for CreateDataAgentSync", - "file": "geminidataanalytics_v1alpha_generated_data_agent_service_create_data_agent_sync_sync.py", + "description": "Sample for CreateDataAgent", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_create_data_agent_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_CreateDataAgentSync_sync", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_CreateDataAgent_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -176,17 +852,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1alpha_generated_data_agent_service_create_data_agent_sync_sync.py" + "title": "geminidataanalytics_v1alpha_generated_data_agent_service_create_data_agent_sync.py" }, { "canonical": true, @@ -196,30 +872,177 @@ "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient", "shortName": "DataAgentServiceAsyncClient" }, - "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient.create_data_agent", + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient.delete_data_agent_sync", "method": { - "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.CreateDataAgent", + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.DeleteDataAgentSync", "service": { "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "CreateDataAgent" + "shortName": "DeleteDataAgentSync" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1alpha.types.CreateDataAgentRequest" + "type": "google.cloud.geminidataanalytics_v1alpha.types.DeleteDataAgentRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { - "name": "data_agent", - "type": "google.cloud.geminidataanalytics_v1alpha.types.DataAgent" + "name": "retry", + "type": "google.api_core.retry.Retry" }, { - "name": "data_agent_id", + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_data_agent_sync" + }, + "description": "Sample for DeleteDataAgentSync", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_delete_data_agent_sync_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_DeleteDataAgentSync_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1alpha_generated_data_agent_service_delete_data_agent_sync_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient", + "shortName": "DataAgentServiceClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.delete_data_agent_sync", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.DeleteDataAgentSync", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", + "shortName": "DataAgentService" + }, + "shortName": "DeleteDataAgentSync" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1alpha.types.DeleteDataAgentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_data_agent_sync" + }, + "description": "Sample for DeleteDataAgentSync", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_delete_data_agent_sync_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_DeleteDataAgentSync_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1alpha_generated_data_agent_service_delete_data_agent_sync_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient", + "shortName": "DataAgentServiceAsyncClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient.delete_data_agent", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.DeleteDataAgent", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", + "shortName": "DataAgentService" + }, + "shortName": "DeleteDataAgent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1alpha.types.DeleteDataAgentRequest" + }, + { + "name": "name", "type": "str" }, { @@ -236,13 +1059,13 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_data_agent" + "shortName": "delete_data_agent" }, - "description": "Sample for CreateDataAgent", - "file": "geminidataanalytics_v1alpha_generated_data_agent_service_create_data_agent_async.py", + "description": "Sample for DeleteDataAgent", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_delete_data_agent_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_CreateDataAgent_async", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_DeleteDataAgent_async", "segments": [ { "end": 55, @@ -275,7 +1098,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1alpha_generated_data_agent_service_create_data_agent_async.py" + "title": "geminidataanalytics_v1alpha_generated_data_agent_service_delete_data_agent_async.py" }, { "canonical": true, @@ -284,30 +1107,22 @@ "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient", "shortName": "DataAgentServiceClient" }, - "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.create_data_agent", + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.delete_data_agent", "method": { - "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.CreateDataAgent", + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.DeleteDataAgent", "service": { "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "CreateDataAgent" + "shortName": "DeleteDataAgent" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1alpha.types.CreateDataAgentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "data_agent", - "type": "google.cloud.geminidataanalytics_v1alpha.types.DataAgent" + "type": "google.cloud.geminidataanalytics_v1alpha.types.DeleteDataAgentRequest" }, { - "name": "data_agent_id", + "name": "name", "type": "str" }, { @@ -324,13 +1139,13 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "create_data_agent" + "shortName": "delete_data_agent" }, - "description": "Sample for CreateDataAgent", - "file": "geminidataanalytics_v1alpha_generated_data_agent_service_create_data_agent_sync.py", + "description": "Sample for DeleteDataAgent", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_delete_data_agent_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_CreateDataAgent_sync", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_DeleteDataAgent_sync", "segments": [ { "end": 55, @@ -363,7 +1178,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1alpha_generated_data_agent_service_create_data_agent_sync.py" + "title": "geminidataanalytics_v1alpha_generated_data_agent_service_delete_data_agent_sync.py" }, { "canonical": true, @@ -373,19 +1188,19 @@ "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient", "shortName": "DataAgentServiceAsyncClient" }, - "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient.delete_data_agent_sync", + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient.get_data_agent", "method": { - "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.DeleteDataAgentSync", + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.GetDataAgent", "service": { "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "DeleteDataAgentSync" + "shortName": "GetDataAgent" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1alpha.types.DeleteDataAgentRequest" + "type": "google.cloud.geminidataanalytics_v1alpha.types.GetDataAgentRequest" }, { "name": "name", @@ -404,21 +1219,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_data_agent_sync" + "resultType": "google.cloud.geminidataanalytics_v1alpha.types.DataAgent", + "shortName": "get_data_agent" }, - "description": "Sample for DeleteDataAgentSync", - "file": "geminidataanalytics_v1alpha_generated_data_agent_service_delete_data_agent_sync_async.py", + "description": "Sample for GetDataAgent", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_get_data_agent_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_DeleteDataAgentSync_async", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_GetDataAgent_async", "segments": [ { - "end": 49, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 51, "start": 27, "type": "SHORT" }, @@ -433,15 +1249,17 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1alpha_generated_data_agent_service_delete_data_agent_sync_async.py" + "title": "geminidataanalytics_v1alpha_generated_data_agent_service_get_data_agent_async.py" }, { "canonical": true, @@ -450,19 +1268,19 @@ "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient", "shortName": "DataAgentServiceClient" }, - "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.delete_data_agent_sync", + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.get_data_agent", "method": { - "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.DeleteDataAgentSync", + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.GetDataAgent", "service": { "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "DeleteDataAgentSync" + "shortName": "GetDataAgent" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1alpha.types.DeleteDataAgentRequest" + "type": "google.cloud.geminidataanalytics_v1alpha.types.GetDataAgentRequest" }, { "name": "name", @@ -481,21 +1299,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_data_agent_sync" + "resultType": "google.cloud.geminidataanalytics_v1alpha.types.DataAgent", + "shortName": "get_data_agent" }, - "description": "Sample for DeleteDataAgentSync", - "file": "geminidataanalytics_v1alpha_generated_data_agent_service_delete_data_agent_sync_sync.py", + "description": "Sample for GetDataAgent", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_get_data_agent_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_DeleteDataAgentSync_sync", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_GetDataAgent_sync", "segments": [ { - "end": 49, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 51, "start": 27, "type": "SHORT" }, @@ -510,15 +1329,17 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1alpha_generated_data_agent_service_delete_data_agent_sync_sync.py" + "title": "geminidataanalytics_v1alpha_generated_data_agent_service_get_data_agent_sync.py" }, { "canonical": true, @@ -528,22 +1349,22 @@ "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient", "shortName": "DataAgentServiceAsyncClient" }, - "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient.delete_data_agent", + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient.get_iam_policy", "method": { - "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.DeleteDataAgent", + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.GetIamPolicy", "service": { "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "DeleteDataAgent" + "shortName": "GetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1alpha.types.DeleteDataAgentRequest" + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" }, { - "name": "name", + "name": "resource", "type": "str" }, { @@ -559,47 +1380,47 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_data_agent" + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" }, - "description": "Sample for DeleteDataAgent", - "file": "geminidataanalytics_v1alpha_generated_data_agent_service_delete_data_agent_async.py", + "description": "Sample for GetIamPolicy", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_get_iam_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_DeleteDataAgent_async", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_GetIamPolicy_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, { - "end": 40, - "start": 38, + "end": 41, + "start": 39, "type": "CLIENT_INITIALIZATION" }, { - "end": 45, - "start": 41, + "end": 46, + "start": 42, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1alpha_generated_data_agent_service_delete_data_agent_async.py" + "title": "geminidataanalytics_v1alpha_generated_data_agent_service_get_iam_policy_async.py" }, { "canonical": true, @@ -608,22 +1429,22 @@ "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient", "shortName": "DataAgentServiceClient" }, - "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.delete_data_agent", + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.get_iam_policy", "method": { - "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.DeleteDataAgent", + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.GetIamPolicy", "service": { "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "DeleteDataAgent" + "shortName": "GetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1alpha.types.DeleteDataAgentRequest" + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" }, { - "name": "name", + "name": "resource", "type": "str" }, { @@ -639,47 +1460,47 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_data_agent" + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" }, - "description": "Sample for DeleteDataAgent", - "file": "geminidataanalytics_v1alpha_generated_data_agent_service_delete_data_agent_sync.py", + "description": "Sample for GetIamPolicy", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_get_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_DeleteDataAgent_sync", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_GetIamPolicy_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, { - "end": 40, - "start": 38, + "end": 41, + "start": 39, "type": "CLIENT_INITIALIZATION" }, { - "end": 45, - "start": 41, + "end": 46, + "start": 42, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1alpha_generated_data_agent_service_delete_data_agent_sync.py" + "title": "geminidataanalytics_v1alpha_generated_data_agent_service_get_iam_policy_sync.py" }, { "canonical": true, @@ -689,22 +1510,22 @@ "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient", "shortName": "DataAgentServiceAsyncClient" }, - "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient.get_data_agent", + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient.list_accessible_data_agents", "method": { - "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.GetDataAgent", + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.ListAccessibleDataAgents", "service": { "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "GetDataAgent" + "shortName": "ListAccessibleDataAgents" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1alpha.types.GetDataAgentRequest" + "type": "google.cloud.geminidataanalytics_v1alpha.types.ListAccessibleDataAgentsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -720,22 +1541,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.geminidataanalytics_v1alpha.types.DataAgent", - "shortName": "get_data_agent" + "resultType": "google.cloud.geminidataanalytics_v1alpha.services.data_agent_service.pagers.ListAccessibleDataAgentsAsyncPager", + "shortName": "list_accessible_data_agents" }, - "description": "Sample for GetDataAgent", - "file": "geminidataanalytics_v1alpha_generated_data_agent_service_get_data_agent_async.py", + "description": "Sample for ListAccessibleDataAgents", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_list_accessible_data_agents_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_GetDataAgent_async", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_ListAccessibleDataAgents_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -755,12 +1576,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1alpha_generated_data_agent_service_get_data_agent_async.py" + "title": "geminidataanalytics_v1alpha_generated_data_agent_service_list_accessible_data_agents_async.py" }, { "canonical": true, @@ -769,22 +1590,22 @@ "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient", "shortName": "DataAgentServiceClient" }, - "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.get_data_agent", + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.list_accessible_data_agents", "method": { - "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.GetDataAgent", + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.ListAccessibleDataAgents", "service": { "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "GetDataAgent" + "shortName": "ListAccessibleDataAgents" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1alpha.types.GetDataAgentRequest" + "type": "google.cloud.geminidataanalytics_v1alpha.types.ListAccessibleDataAgentsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -800,22 +1621,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.geminidataanalytics_v1alpha.types.DataAgent", - "shortName": "get_data_agent" + "resultType": "google.cloud.geminidataanalytics_v1alpha.services.data_agent_service.pagers.ListAccessibleDataAgentsPager", + "shortName": "list_accessible_data_agents" }, - "description": "Sample for GetDataAgent", - "file": "geminidataanalytics_v1alpha_generated_data_agent_service_get_data_agent_sync.py", + "description": "Sample for ListAccessibleDataAgents", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_list_accessible_data_agents_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_GetDataAgent_sync", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_ListAccessibleDataAgents_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -835,12 +1656,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1alpha_generated_data_agent_service_get_data_agent_sync.py" + "title": "geminidataanalytics_v1alpha_generated_data_agent_service_list_accessible_data_agents_sync.py" }, { "canonical": true, @@ -850,22 +1671,22 @@ "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient", "shortName": "DataAgentServiceAsyncClient" }, - "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient.get_iam_policy", + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient.list_data_agents", "method": { - "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.GetIamPolicy", + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.ListDataAgents", "service": { "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "GetIamPolicy" + "shortName": "ListDataAgents" }, "parameters": [ { "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + "type": "google.cloud.geminidataanalytics_v1alpha.types.ListDataAgentsRequest" }, { - "name": "resource", + "name": "parent", "type": "str" }, { @@ -881,14 +1702,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" + "resultType": "google.cloud.geminidataanalytics_v1alpha.services.data_agent_service.pagers.ListDataAgentsAsyncPager", + "shortName": "list_data_agents" }, - "description": "Sample for GetIamPolicy", - "file": "geminidataanalytics_v1alpha_generated_data_agent_service_get_iam_policy_async.py", + "description": "Sample for ListDataAgents", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_list_data_agents_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_GetIamPolicy_async", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_ListDataAgents_async", "segments": [ { "end": 52, @@ -901,27 +1722,27 @@ "type": "SHORT" }, { - "end": 41, - "start": 39, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 46, - "start": 42, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1alpha_generated_data_agent_service_get_iam_policy_async.py" + "title": "geminidataanalytics_v1alpha_generated_data_agent_service_list_data_agents_async.py" }, { "canonical": true, @@ -930,22 +1751,22 @@ "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient", "shortName": "DataAgentServiceClient" }, - "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.get_iam_policy", + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.list_data_agents", "method": { - "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.GetIamPolicy", + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.ListDataAgents", "service": { "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "GetIamPolicy" + "shortName": "ListDataAgents" }, "parameters": [ { "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + "type": "google.cloud.geminidataanalytics_v1alpha.types.ListDataAgentsRequest" }, { - "name": "resource", + "name": "parent", "type": "str" }, { @@ -961,14 +1782,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" + "resultType": "google.cloud.geminidataanalytics_v1alpha.services.data_agent_service.pagers.ListDataAgentsPager", + "shortName": "list_data_agents" }, - "description": "Sample for GetIamPolicy", - "file": "geminidataanalytics_v1alpha_generated_data_agent_service_get_iam_policy_sync.py", + "description": "Sample for ListDataAgents", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_list_data_agents_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_GetIamPolicy_sync", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_ListDataAgents_sync", "segments": [ { "end": 52, @@ -981,27 +1802,27 @@ "type": "SHORT" }, { - "end": 41, - "start": 39, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 46, - "start": 42, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1alpha_generated_data_agent_service_get_iam_policy_sync.py" + "title": "geminidataanalytics_v1alpha_generated_data_agent_service_list_data_agents_sync.py" }, { "canonical": true, @@ -1011,24 +1832,28 @@ "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient", "shortName": "DataAgentServiceAsyncClient" }, - "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient.list_accessible_data_agents", + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient.retrieve_agent_ops_observability", "method": { - "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.ListAccessibleDataAgents", + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.RetrieveAgentOpsObservability", "service": { "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "ListAccessibleDataAgents" + "shortName": "RetrieveAgentOpsObservability" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1alpha.types.ListAccessibleDataAgentsRequest" + "type": "google.cloud.geminidataanalytics_v1alpha.types.RetrieveAgentOpsObservabilityRequest" }, { "name": "parent", "type": "str" }, + { + "name": "data_source_type", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1042,14 +1867,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.geminidataanalytics_v1alpha.services.data_agent_service.pagers.ListAccessibleDataAgentsAsyncPager", - "shortName": "list_accessible_data_agents" + "resultType": "google.cloud.geminidataanalytics_v1alpha.types.RetrieveAgentOpsObservabilityResponse", + "shortName": "retrieve_agent_ops_observability" }, - "description": "Sample for ListAccessibleDataAgents", - "file": "geminidataanalytics_v1alpha_generated_data_agent_service_list_accessible_data_agents_async.py", + "description": "Sample for RetrieveAgentOpsObservability", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_retrieve_agent_ops_observability_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_ListAccessibleDataAgents_async", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_RetrieveAgentOpsObservability_async", "segments": [ { "end": 52, @@ -1067,22 +1892,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 49, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1alpha_generated_data_agent_service_list_accessible_data_agents_async.py" + "title": "geminidataanalytics_v1alpha_generated_data_agent_service_retrieve_agent_ops_observability_async.py" }, { "canonical": true, @@ -1091,24 +1916,28 @@ "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient", "shortName": "DataAgentServiceClient" }, - "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.list_accessible_data_agents", + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.retrieve_agent_ops_observability", "method": { - "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.ListAccessibleDataAgents", + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.RetrieveAgentOpsObservability", "service": { "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "ListAccessibleDataAgents" + "shortName": "RetrieveAgentOpsObservability" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1alpha.types.ListAccessibleDataAgentsRequest" + "type": "google.cloud.geminidataanalytics_v1alpha.types.RetrieveAgentOpsObservabilityRequest" }, { "name": "parent", "type": "str" }, + { + "name": "data_source_type", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1122,14 +1951,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.geminidataanalytics_v1alpha.services.data_agent_service.pagers.ListAccessibleDataAgentsPager", - "shortName": "list_accessible_data_agents" + "resultType": "google.cloud.geminidataanalytics_v1alpha.types.RetrieveAgentOpsObservabilityResponse", + "shortName": "retrieve_agent_ops_observability" }, - "description": "Sample for ListAccessibleDataAgents", - "file": "geminidataanalytics_v1alpha_generated_data_agent_service_list_accessible_data_agents_sync.py", + "description": "Sample for RetrieveAgentOpsObservability", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_retrieve_agent_ops_observability_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_ListAccessibleDataAgents_sync", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_RetrieveAgentOpsObservability_sync", "segments": [ { "end": 52, @@ -1147,22 +1976,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 49, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1alpha_generated_data_agent_service_list_accessible_data_agents_sync.py" + "title": "geminidataanalytics_v1alpha_generated_data_agent_service_retrieve_agent_ops_observability_sync.py" }, { "canonical": true, @@ -1172,24 +2001,32 @@ "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient", "shortName": "DataAgentServiceAsyncClient" }, - "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient.list_data_agents", + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceAsyncClient.set_agent_ops_observability", "method": { - "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.ListDataAgents", + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.SetAgentOpsObservability", "service": { "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "ListDataAgents" + "shortName": "SetAgentOpsObservability" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1alpha.types.ListDataAgentsRequest" + "type": "google.cloud.geminidataanalytics_v1alpha.types.SetAgentOpsObservabilityRequest" }, { "name": "parent", "type": "str" }, + { + "name": "telemetry_enabled", + "type": "bool" + }, + { + "name": "data_source_type", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1203,22 +2040,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.geminidataanalytics_v1alpha.services.data_agent_service.pagers.ListDataAgentsAsyncPager", - "shortName": "list_data_agents" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "set_agent_ops_observability" }, - "description": "Sample for ListDataAgents", - "file": "geminidataanalytics_v1alpha_generated_data_agent_service_list_data_agents_async.py", + "description": "Sample for SetAgentOpsObservability", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_set_agent_ops_observability_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_ListDataAgents_async", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_SetAgentOpsObservability_async", "segments": [ { - "end": 52, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 56, "start": 27, "type": "SHORT" }, @@ -1228,22 +2065,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1alpha_generated_data_agent_service_list_data_agents_async.py" + "title": "geminidataanalytics_v1alpha_generated_data_agent_service_set_agent_ops_observability_async.py" }, { "canonical": true, @@ -1252,24 +2089,32 @@ "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient", "shortName": "DataAgentServiceClient" }, - "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.list_data_agents", + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataAgentServiceClient.set_agent_ops_observability", "method": { - "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.ListDataAgents", + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService.SetAgentOpsObservability", "service": { "fullName": "google.cloud.geminidataanalytics.v1alpha.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "ListDataAgents" + "shortName": "SetAgentOpsObservability" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1alpha.types.ListDataAgentsRequest" + "type": "google.cloud.geminidataanalytics_v1alpha.types.SetAgentOpsObservabilityRequest" }, { "name": "parent", "type": "str" }, + { + "name": "telemetry_enabled", + "type": "bool" + }, + { + "name": "data_source_type", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1283,22 +2128,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.geminidataanalytics_v1alpha.services.data_agent_service.pagers.ListDataAgentsPager", - "shortName": "list_data_agents" + "resultType": "google.api_core.operation.Operation", + "shortName": "set_agent_ops_observability" }, - "description": "Sample for ListDataAgents", - "file": "geminidataanalytics_v1alpha_generated_data_agent_service_list_data_agents_sync.py", + "description": "Sample for SetAgentOpsObservability", + "file": "geminidataanalytics_v1alpha_generated_data_agent_service_set_agent_ops_observability_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_ListDataAgents_sync", + "regionTag": "geminidataanalytics_v1alpha_generated_DataAgentService_SetAgentOpsObservability_sync", "segments": [ { - "end": 52, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 56, "start": 27, "type": "SHORT" }, @@ -1308,22 +2153,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1alpha_generated_data_agent_service_list_data_agents_sync.py" + "title": "geminidataanalytics_v1alpha_generated_data_agent_service_set_agent_ops_observability_sync.py" }, { "canonical": true, @@ -2944,6 +3789,175 @@ } ], "title": "geminidataanalytics_v1alpha_generated_data_chat_service_query_data_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataChatServiceAsyncClient", + "shortName": "DataChatServiceAsyncClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataChatServiceAsyncClient.update_conversation", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataChatService.UpdateConversation", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataChatService", + "shortName": "DataChatService" + }, + "shortName": "UpdateConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1alpha.types.UpdateConversationRequest" + }, + { + "name": "conversation", + "type": "google.cloud.geminidataanalytics_v1alpha.types.Conversation" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1alpha.types.Conversation", + "shortName": "update_conversation" + }, + "description": "Sample for UpdateConversation", + "file": "geminidataanalytics_v1alpha_generated_data_chat_service_update_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1alpha_generated_DataChatService_UpdateConversation_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1alpha_generated_data_chat_service_update_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataChatServiceClient", + "shortName": "DataChatServiceClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1alpha.DataChatServiceClient.update_conversation", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataChatService.UpdateConversation", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1alpha.DataChatService", + "shortName": "DataChatService" + }, + "shortName": "UpdateConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1alpha.types.UpdateConversationRequest" + }, + { + "name": "conversation", + "type": "google.cloud.geminidataanalytics_v1alpha.types.Conversation" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1alpha.types.Conversation", + "shortName": "update_conversation" + }, + "description": "Sample for UpdateConversation", + "file": "geminidataanalytics_v1alpha_generated_data_chat_service_update_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1alpha_generated_DataChatService_UpdateConversation_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1alpha_generated_data_chat_service_update_conversation_sync.py" } ] } diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1beta.json b/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1beta.json index 0a41171df075..403cd42e89e2 100644 --- a/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1beta.json +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1beta.json @@ -11,6 +11,505 @@ "version": "0.13.3" }, "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.geminidataanalytics_v1beta.DataA2AServiceAsyncClient", + "shortName": "DataA2AServiceAsyncClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1beta.DataA2AServiceAsyncClient.get_agent_card", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataA2AService.GetAgentCard", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "shortName": "DataA2AService" + }, + "shortName": "GetAgentCard" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1beta.types.GetAgentCardRequest" + }, + { + "name": "tenant", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1beta.types.AgentCard", + "shortName": "get_agent_card" + }, + "description": "Sample for GetAgentCard", + "file": "geminidataanalytics_v1beta_generated_data_a2a_service_get_agent_card_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1beta_generated_DataA2AService_GetAgentCard_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1beta_generated_data_a2a_service_get_agent_card_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.geminidataanalytics_v1beta.DataA2AServiceClient", + "shortName": "DataA2AServiceClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1beta.DataA2AServiceClient.get_agent_card", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataA2AService.GetAgentCard", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "shortName": "DataA2AService" + }, + "shortName": "GetAgentCard" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1beta.types.GetAgentCardRequest" + }, + { + "name": "tenant", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1beta.types.AgentCard", + "shortName": "get_agent_card" + }, + "description": "Sample for GetAgentCard", + "file": "geminidataanalytics_v1beta_generated_data_a2a_service_get_agent_card_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1beta_generated_DataA2AService_GetAgentCard_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1beta_generated_data_a2a_service_get_agent_card_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.geminidataanalytics_v1beta.DataA2AServiceAsyncClient", + "shortName": "DataA2AServiceAsyncClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1beta.DataA2AServiceAsyncClient.send_message", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataA2AService.SendMessage", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "shortName": "DataA2AService" + }, + "shortName": "SendMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1beta.types.SendMessageRequest" + }, + { + "name": "tenant", + "type": "str" + }, + { + "name": "message", + "type": "google.cloud.geminidataanalytics_v1beta.types.A2AMessage" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1beta.types.SendMessageResponse", + "shortName": "send_message" + }, + "description": "Sample for SendMessage", + "file": "geminidataanalytics_v1beta_generated_data_a2a_service_send_message_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1beta_generated_DataA2AService_SendMessage_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1beta_generated_data_a2a_service_send_message_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.geminidataanalytics_v1beta.DataA2AServiceClient", + "shortName": "DataA2AServiceClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1beta.DataA2AServiceClient.send_message", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataA2AService.SendMessage", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "shortName": "DataA2AService" + }, + "shortName": "SendMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1beta.types.SendMessageRequest" + }, + { + "name": "tenant", + "type": "str" + }, + { + "name": "message", + "type": "google.cloud.geminidataanalytics_v1beta.types.A2AMessage" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1beta.types.SendMessageResponse", + "shortName": "send_message" + }, + "description": "Sample for SendMessage", + "file": "geminidataanalytics_v1beta_generated_data_a2a_service_send_message_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1beta_generated_DataA2AService_SendMessage_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1beta_generated_data_a2a_service_send_message_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.geminidataanalytics_v1beta.DataA2AServiceAsyncClient", + "shortName": "DataA2AServiceAsyncClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1beta.DataA2AServiceAsyncClient.send_streaming_message", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataA2AService.SendStreamingMessage", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "shortName": "DataA2AService" + }, + "shortName": "SendStreamingMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1beta.types.SendMessageRequest" + }, + { + "name": "tenant", + "type": "str" + }, + { + "name": "message", + "type": "google.cloud.geminidataanalytics_v1beta.types.A2AMessage" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.cloud.geminidataanalytics_v1beta.types.StreamResponse]", + "shortName": "send_streaming_message" + }, + "description": "Sample for SendStreamingMessage", + "file": "geminidataanalytics_v1beta_generated_data_a2a_service_send_streaming_message_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1beta_generated_DataA2AService_SendStreamingMessage_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1beta_generated_data_a2a_service_send_streaming_message_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.geminidataanalytics_v1beta.DataA2AServiceClient", + "shortName": "DataA2AServiceClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1beta.DataA2AServiceClient.send_streaming_message", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataA2AService.SendStreamingMessage", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataA2AService", + "shortName": "DataA2AService" + }, + "shortName": "SendStreamingMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1beta.types.SendMessageRequest" + }, + { + "name": "tenant", + "type": "str" + }, + { + "name": "message", + "type": "google.cloud.geminidataanalytics_v1beta.types.A2AMessage" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.cloud.geminidataanalytics_v1beta.types.StreamResponse]", + "shortName": "send_streaming_message" + }, + "description": "Sample for SendStreamingMessage", + "file": "geminidataanalytics_v1beta_generated_data_a2a_service_send_streaming_message_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1beta_generated_DataA2AService_SendStreamingMessage_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1beta_generated_data_a2a_service_send_streaming_message_sync.py" + }, { "canonical": true, "clientMethod": { @@ -58,22 +557,199 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.geminidataanalytics_v1beta.types.DataAgent", - "shortName": "create_data_agent_sync" + "resultType": "google.cloud.geminidataanalytics_v1beta.types.DataAgent", + "shortName": "create_data_agent_sync" + }, + "description": "Sample for CreateDataAgentSync", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_create_data_agent_sync_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_CreateDataAgentSync_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": "geminidataanalytics_v1beta_generated_data_agent_service_create_data_agent_sync_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient", + "shortName": "DataAgentServiceClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.create_data_agent_sync", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.CreateDataAgentSync", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", + "shortName": "DataAgentService" + }, + "shortName": "CreateDataAgentSync" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1beta.types.CreateDataAgentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "data_agent", + "type": "google.cloud.geminidataanalytics_v1beta.types.DataAgent" + }, + { + "name": "data_agent_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1beta.types.DataAgent", + "shortName": "create_data_agent_sync" + }, + "description": "Sample for CreateDataAgentSync", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_create_data_agent_sync_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_CreateDataAgentSync_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": "geminidataanalytics_v1beta_generated_data_agent_service_create_data_agent_sync_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient", + "shortName": "DataAgentServiceAsyncClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient.create_data_agent", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.CreateDataAgent", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", + "shortName": "DataAgentService" + }, + "shortName": "CreateDataAgent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1beta.types.CreateDataAgentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "data_agent", + "type": "google.cloud.geminidataanalytics_v1beta.types.DataAgent" + }, + { + "name": "data_agent_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_data_agent" }, - "description": "Sample for CreateDataAgentSync", - "file": "geminidataanalytics_v1beta_generated_data_agent_service_create_data_agent_sync_async.py", + "description": "Sample for CreateDataAgent", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_create_data_agent_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_CreateDataAgentSync_async", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_CreateDataAgent_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -88,17 +764,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1beta_generated_data_agent_service_create_data_agent_sync_async.py" + "title": "geminidataanalytics_v1beta_generated_data_agent_service_create_data_agent_async.py" }, { "canonical": true, @@ -107,14 +783,14 @@ "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient", "shortName": "DataAgentServiceClient" }, - "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.create_data_agent_sync", + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.create_data_agent", "method": { - "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.CreateDataAgentSync", + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.CreateDataAgent", "service": { "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "CreateDataAgentSync" + "shortName": "CreateDataAgent" }, "parameters": [ { @@ -146,22 +822,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.geminidataanalytics_v1beta.types.DataAgent", - "shortName": "create_data_agent_sync" + "resultType": "google.api_core.operation.Operation", + "shortName": "create_data_agent" }, - "description": "Sample for CreateDataAgentSync", - "file": "geminidataanalytics_v1beta_generated_data_agent_service_create_data_agent_sync_sync.py", + "description": "Sample for CreateDataAgent", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_create_data_agent_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_CreateDataAgentSync_sync", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_CreateDataAgent_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -176,17 +852,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1beta_generated_data_agent_service_create_data_agent_sync_sync.py" + "title": "geminidataanalytics_v1beta_generated_data_agent_service_create_data_agent_sync.py" }, { "canonical": true, @@ -196,30 +872,177 @@ "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient", "shortName": "DataAgentServiceAsyncClient" }, - "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient.create_data_agent", + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient.delete_data_agent_sync", "method": { - "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.CreateDataAgent", + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.DeleteDataAgentSync", "service": { "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "CreateDataAgent" + "shortName": "DeleteDataAgentSync" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1beta.types.CreateDataAgentRequest" + "type": "google.cloud.geminidataanalytics_v1beta.types.DeleteDataAgentRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { - "name": "data_agent", - "type": "google.cloud.geminidataanalytics_v1beta.types.DataAgent" + "name": "retry", + "type": "google.api_core.retry.Retry" }, { - "name": "data_agent_id", + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_data_agent_sync" + }, + "description": "Sample for DeleteDataAgentSync", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_delete_data_agent_sync_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_DeleteDataAgentSync_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1beta_generated_data_agent_service_delete_data_agent_sync_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient", + "shortName": "DataAgentServiceClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.delete_data_agent_sync", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.DeleteDataAgentSync", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", + "shortName": "DataAgentService" + }, + "shortName": "DeleteDataAgentSync" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1beta.types.DeleteDataAgentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_data_agent_sync" + }, + "description": "Sample for DeleteDataAgentSync", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_delete_data_agent_sync_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_DeleteDataAgentSync_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1beta_generated_data_agent_service_delete_data_agent_sync_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient", + "shortName": "DataAgentServiceAsyncClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient.delete_data_agent", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.DeleteDataAgent", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", + "shortName": "DataAgentService" + }, + "shortName": "DeleteDataAgent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1beta.types.DeleteDataAgentRequest" + }, + { + "name": "name", "type": "str" }, { @@ -236,13 +1059,13 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_data_agent" + "shortName": "delete_data_agent" }, - "description": "Sample for CreateDataAgent", - "file": "geminidataanalytics_v1beta_generated_data_agent_service_create_data_agent_async.py", + "description": "Sample for DeleteDataAgent", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_delete_data_agent_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_CreateDataAgent_async", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_DeleteDataAgent_async", "segments": [ { "end": 55, @@ -275,7 +1098,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1beta_generated_data_agent_service_create_data_agent_async.py" + "title": "geminidataanalytics_v1beta_generated_data_agent_service_delete_data_agent_async.py" }, { "canonical": true, @@ -284,30 +1107,22 @@ "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient", "shortName": "DataAgentServiceClient" }, - "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.create_data_agent", + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.delete_data_agent", "method": { - "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.CreateDataAgent", + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.DeleteDataAgent", "service": { "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "CreateDataAgent" + "shortName": "DeleteDataAgent" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1beta.types.CreateDataAgentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "data_agent", - "type": "google.cloud.geminidataanalytics_v1beta.types.DataAgent" + "type": "google.cloud.geminidataanalytics_v1beta.types.DeleteDataAgentRequest" }, { - "name": "data_agent_id", + "name": "name", "type": "str" }, { @@ -324,13 +1139,13 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "create_data_agent" + "shortName": "delete_data_agent" }, - "description": "Sample for CreateDataAgent", - "file": "geminidataanalytics_v1beta_generated_data_agent_service_create_data_agent_sync.py", + "description": "Sample for DeleteDataAgent", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_delete_data_agent_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_CreateDataAgent_sync", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_DeleteDataAgent_sync", "segments": [ { "end": 55, @@ -363,7 +1178,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1beta_generated_data_agent_service_create_data_agent_sync.py" + "title": "geminidataanalytics_v1beta_generated_data_agent_service_delete_data_agent_sync.py" }, { "canonical": true, @@ -373,19 +1188,19 @@ "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient", "shortName": "DataAgentServiceAsyncClient" }, - "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient.delete_data_agent_sync", + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient.get_data_agent", "method": { - "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.DeleteDataAgentSync", + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.GetDataAgent", "service": { "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "DeleteDataAgentSync" + "shortName": "GetDataAgent" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1beta.types.DeleteDataAgentRequest" + "type": "google.cloud.geminidataanalytics_v1beta.types.GetDataAgentRequest" }, { "name": "name", @@ -404,21 +1219,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_data_agent_sync" + "resultType": "google.cloud.geminidataanalytics_v1beta.types.DataAgent", + "shortName": "get_data_agent" }, - "description": "Sample for DeleteDataAgentSync", - "file": "geminidataanalytics_v1beta_generated_data_agent_service_delete_data_agent_sync_async.py", + "description": "Sample for GetDataAgent", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_get_data_agent_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_DeleteDataAgentSync_async", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_GetDataAgent_async", "segments": [ { - "end": 49, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 51, "start": 27, "type": "SHORT" }, @@ -433,15 +1249,17 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1beta_generated_data_agent_service_delete_data_agent_sync_async.py" + "title": "geminidataanalytics_v1beta_generated_data_agent_service_get_data_agent_async.py" }, { "canonical": true, @@ -450,19 +1268,19 @@ "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient", "shortName": "DataAgentServiceClient" }, - "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.delete_data_agent_sync", + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.get_data_agent", "method": { - "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.DeleteDataAgentSync", + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.GetDataAgent", "service": { "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "DeleteDataAgentSync" + "shortName": "GetDataAgent" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1beta.types.DeleteDataAgentRequest" + "type": "google.cloud.geminidataanalytics_v1beta.types.GetDataAgentRequest" }, { "name": "name", @@ -481,21 +1299,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_data_agent_sync" + "resultType": "google.cloud.geminidataanalytics_v1beta.types.DataAgent", + "shortName": "get_data_agent" }, - "description": "Sample for DeleteDataAgentSync", - "file": "geminidataanalytics_v1beta_generated_data_agent_service_delete_data_agent_sync_sync.py", + "description": "Sample for GetDataAgent", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_get_data_agent_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_DeleteDataAgentSync_sync", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_GetDataAgent_sync", "segments": [ { - "end": 49, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 51, "start": 27, "type": "SHORT" }, @@ -510,15 +1329,17 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1beta_generated_data_agent_service_delete_data_agent_sync_sync.py" + "title": "geminidataanalytics_v1beta_generated_data_agent_service_get_data_agent_sync.py" }, { "canonical": true, @@ -528,22 +1349,22 @@ "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient", "shortName": "DataAgentServiceAsyncClient" }, - "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient.delete_data_agent", + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient.get_iam_policy", "method": { - "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.DeleteDataAgent", + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.GetIamPolicy", "service": { "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "DeleteDataAgent" + "shortName": "GetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1beta.types.DeleteDataAgentRequest" + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" }, { - "name": "name", + "name": "resource", "type": "str" }, { @@ -559,47 +1380,47 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_data_agent" + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" }, - "description": "Sample for DeleteDataAgent", - "file": "geminidataanalytics_v1beta_generated_data_agent_service_delete_data_agent_async.py", + "description": "Sample for GetIamPolicy", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_get_iam_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_DeleteDataAgent_async", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_GetIamPolicy_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, { - "end": 40, - "start": 38, + "end": 41, + "start": 39, "type": "CLIENT_INITIALIZATION" }, { - "end": 45, - "start": 41, + "end": 46, + "start": 42, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1beta_generated_data_agent_service_delete_data_agent_async.py" + "title": "geminidataanalytics_v1beta_generated_data_agent_service_get_iam_policy_async.py" }, { "canonical": true, @@ -608,22 +1429,22 @@ "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient", "shortName": "DataAgentServiceClient" }, - "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.delete_data_agent", + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.get_iam_policy", "method": { - "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.DeleteDataAgent", + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.GetIamPolicy", "service": { "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "DeleteDataAgent" + "shortName": "GetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1beta.types.DeleteDataAgentRequest" + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" }, { - "name": "name", + "name": "resource", "type": "str" }, { @@ -639,47 +1460,47 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_data_agent" + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" }, - "description": "Sample for DeleteDataAgent", - "file": "geminidataanalytics_v1beta_generated_data_agent_service_delete_data_agent_sync.py", + "description": "Sample for GetIamPolicy", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_get_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_DeleteDataAgent_sync", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_GetIamPolicy_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, { - "end": 40, - "start": 38, + "end": 41, + "start": 39, "type": "CLIENT_INITIALIZATION" }, { - "end": 45, - "start": 41, + "end": 46, + "start": 42, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1beta_generated_data_agent_service_delete_data_agent_sync.py" + "title": "geminidataanalytics_v1beta_generated_data_agent_service_get_iam_policy_sync.py" }, { "canonical": true, @@ -689,22 +1510,22 @@ "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient", "shortName": "DataAgentServiceAsyncClient" }, - "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient.get_data_agent", + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient.list_accessible_data_agents", "method": { - "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.GetDataAgent", + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.ListAccessibleDataAgents", "service": { "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "GetDataAgent" + "shortName": "ListAccessibleDataAgents" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1beta.types.GetDataAgentRequest" + "type": "google.cloud.geminidataanalytics_v1beta.types.ListAccessibleDataAgentsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -720,22 +1541,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.geminidataanalytics_v1beta.types.DataAgent", - "shortName": "get_data_agent" + "resultType": "google.cloud.geminidataanalytics_v1beta.services.data_agent_service.pagers.ListAccessibleDataAgentsAsyncPager", + "shortName": "list_accessible_data_agents" }, - "description": "Sample for GetDataAgent", - "file": "geminidataanalytics_v1beta_generated_data_agent_service_get_data_agent_async.py", + "description": "Sample for ListAccessibleDataAgents", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_list_accessible_data_agents_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_GetDataAgent_async", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_ListAccessibleDataAgents_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -755,12 +1576,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1beta_generated_data_agent_service_get_data_agent_async.py" + "title": "geminidataanalytics_v1beta_generated_data_agent_service_list_accessible_data_agents_async.py" }, { "canonical": true, @@ -769,22 +1590,22 @@ "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient", "shortName": "DataAgentServiceClient" }, - "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.get_data_agent", + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.list_accessible_data_agents", "method": { - "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.GetDataAgent", + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.ListAccessibleDataAgents", "service": { "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "GetDataAgent" + "shortName": "ListAccessibleDataAgents" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1beta.types.GetDataAgentRequest" + "type": "google.cloud.geminidataanalytics_v1beta.types.ListAccessibleDataAgentsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -800,22 +1621,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.geminidataanalytics_v1beta.types.DataAgent", - "shortName": "get_data_agent" + "resultType": "google.cloud.geminidataanalytics_v1beta.services.data_agent_service.pagers.ListAccessibleDataAgentsPager", + "shortName": "list_accessible_data_agents" }, - "description": "Sample for GetDataAgent", - "file": "geminidataanalytics_v1beta_generated_data_agent_service_get_data_agent_sync.py", + "description": "Sample for ListAccessibleDataAgents", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_list_accessible_data_agents_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_GetDataAgent_sync", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_ListAccessibleDataAgents_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -835,12 +1656,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1beta_generated_data_agent_service_get_data_agent_sync.py" + "title": "geminidataanalytics_v1beta_generated_data_agent_service_list_accessible_data_agents_sync.py" }, { "canonical": true, @@ -850,22 +1671,22 @@ "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient", "shortName": "DataAgentServiceAsyncClient" }, - "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient.get_iam_policy", + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient.list_data_agents", "method": { - "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.GetIamPolicy", + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.ListDataAgents", "service": { "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "GetIamPolicy" + "shortName": "ListDataAgents" }, "parameters": [ { "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + "type": "google.cloud.geminidataanalytics_v1beta.types.ListDataAgentsRequest" }, { - "name": "resource", + "name": "parent", "type": "str" }, { @@ -881,14 +1702,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" + "resultType": "google.cloud.geminidataanalytics_v1beta.services.data_agent_service.pagers.ListDataAgentsAsyncPager", + "shortName": "list_data_agents" }, - "description": "Sample for GetIamPolicy", - "file": "geminidataanalytics_v1beta_generated_data_agent_service_get_iam_policy_async.py", + "description": "Sample for ListDataAgents", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_list_data_agents_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_GetIamPolicy_async", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_ListDataAgents_async", "segments": [ { "end": 52, @@ -901,27 +1722,27 @@ "type": "SHORT" }, { - "end": 41, - "start": 39, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 46, - "start": 42, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1beta_generated_data_agent_service_get_iam_policy_async.py" + "title": "geminidataanalytics_v1beta_generated_data_agent_service_list_data_agents_async.py" }, { "canonical": true, @@ -930,22 +1751,22 @@ "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient", "shortName": "DataAgentServiceClient" }, - "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.get_iam_policy", + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.list_data_agents", "method": { - "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.GetIamPolicy", + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.ListDataAgents", "service": { "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "GetIamPolicy" + "shortName": "ListDataAgents" }, "parameters": [ { "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + "type": "google.cloud.geminidataanalytics_v1beta.types.ListDataAgentsRequest" }, { - "name": "resource", + "name": "parent", "type": "str" }, { @@ -961,14 +1782,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" + "resultType": "google.cloud.geminidataanalytics_v1beta.services.data_agent_service.pagers.ListDataAgentsPager", + "shortName": "list_data_agents" }, - "description": "Sample for GetIamPolicy", - "file": "geminidataanalytics_v1beta_generated_data_agent_service_get_iam_policy_sync.py", + "description": "Sample for ListDataAgents", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_list_data_agents_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_GetIamPolicy_sync", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_ListDataAgents_sync", "segments": [ { "end": 52, @@ -981,27 +1802,27 @@ "type": "SHORT" }, { - "end": 41, - "start": 39, + "end": 40, + "start": 38, "type": "CLIENT_INITIALIZATION" }, { - "end": 46, - "start": 42, + "end": 45, + "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1beta_generated_data_agent_service_get_iam_policy_sync.py" + "title": "geminidataanalytics_v1beta_generated_data_agent_service_list_data_agents_sync.py" }, { "canonical": true, @@ -1011,24 +1832,28 @@ "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient", "shortName": "DataAgentServiceAsyncClient" }, - "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient.list_accessible_data_agents", + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient.retrieve_agent_ops_observability", "method": { - "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.ListAccessibleDataAgents", + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.RetrieveAgentOpsObservability", "service": { "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "ListAccessibleDataAgents" + "shortName": "RetrieveAgentOpsObservability" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1beta.types.ListAccessibleDataAgentsRequest" + "type": "google.cloud.geminidataanalytics_v1beta.types.RetrieveAgentOpsObservabilityRequest" }, { "name": "parent", "type": "str" }, + { + "name": "data_source_type", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1042,14 +1867,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.geminidataanalytics_v1beta.services.data_agent_service.pagers.ListAccessibleDataAgentsAsyncPager", - "shortName": "list_accessible_data_agents" + "resultType": "google.cloud.geminidataanalytics_v1beta.types.RetrieveAgentOpsObservabilityResponse", + "shortName": "retrieve_agent_ops_observability" }, - "description": "Sample for ListAccessibleDataAgents", - "file": "geminidataanalytics_v1beta_generated_data_agent_service_list_accessible_data_agents_async.py", + "description": "Sample for RetrieveAgentOpsObservability", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_retrieve_agent_ops_observability_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_ListAccessibleDataAgents_async", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_RetrieveAgentOpsObservability_async", "segments": [ { "end": 52, @@ -1067,22 +1892,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 49, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1beta_generated_data_agent_service_list_accessible_data_agents_async.py" + "title": "geminidataanalytics_v1beta_generated_data_agent_service_retrieve_agent_ops_observability_async.py" }, { "canonical": true, @@ -1091,24 +1916,28 @@ "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient", "shortName": "DataAgentServiceClient" }, - "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.list_accessible_data_agents", + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.retrieve_agent_ops_observability", "method": { - "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.ListAccessibleDataAgents", + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.RetrieveAgentOpsObservability", "service": { "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "ListAccessibleDataAgents" + "shortName": "RetrieveAgentOpsObservability" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1beta.types.ListAccessibleDataAgentsRequest" + "type": "google.cloud.geminidataanalytics_v1beta.types.RetrieveAgentOpsObservabilityRequest" }, { "name": "parent", "type": "str" }, + { + "name": "data_source_type", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1122,14 +1951,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.geminidataanalytics_v1beta.services.data_agent_service.pagers.ListAccessibleDataAgentsPager", - "shortName": "list_accessible_data_agents" + "resultType": "google.cloud.geminidataanalytics_v1beta.types.RetrieveAgentOpsObservabilityResponse", + "shortName": "retrieve_agent_ops_observability" }, - "description": "Sample for ListAccessibleDataAgents", - "file": "geminidataanalytics_v1beta_generated_data_agent_service_list_accessible_data_agents_sync.py", + "description": "Sample for RetrieveAgentOpsObservability", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_retrieve_agent_ops_observability_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_ListAccessibleDataAgents_sync", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_RetrieveAgentOpsObservability_sync", "segments": [ { "end": 52, @@ -1147,22 +1976,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 49, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1beta_generated_data_agent_service_list_accessible_data_agents_sync.py" + "title": "geminidataanalytics_v1beta_generated_data_agent_service_retrieve_agent_ops_observability_sync.py" }, { "canonical": true, @@ -1172,24 +2001,32 @@ "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient", "shortName": "DataAgentServiceAsyncClient" }, - "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient.list_data_agents", + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceAsyncClient.set_agent_ops_observability", "method": { - "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.ListDataAgents", + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.SetAgentOpsObservability", "service": { "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "ListDataAgents" + "shortName": "SetAgentOpsObservability" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1beta.types.ListDataAgentsRequest" + "type": "google.cloud.geminidataanalytics_v1beta.types.SetAgentOpsObservabilityRequest" }, { "name": "parent", "type": "str" }, + { + "name": "telemetry_enabled", + "type": "bool" + }, + { + "name": "data_source_type", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1203,22 +2040,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.geminidataanalytics_v1beta.services.data_agent_service.pagers.ListDataAgentsAsyncPager", - "shortName": "list_data_agents" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "set_agent_ops_observability" }, - "description": "Sample for ListDataAgents", - "file": "geminidataanalytics_v1beta_generated_data_agent_service_list_data_agents_async.py", + "description": "Sample for SetAgentOpsObservability", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_set_agent_ops_observability_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_ListDataAgents_async", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_SetAgentOpsObservability_async", "segments": [ { - "end": 52, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 56, "start": 27, "type": "SHORT" }, @@ -1228,22 +2065,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1beta_generated_data_agent_service_list_data_agents_async.py" + "title": "geminidataanalytics_v1beta_generated_data_agent_service_set_agent_ops_observability_async.py" }, { "canonical": true, @@ -1252,24 +2089,32 @@ "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient", "shortName": "DataAgentServiceClient" }, - "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.list_data_agents", + "fullName": "google.cloud.geminidataanalytics_v1beta.DataAgentServiceClient.set_agent_ops_observability", "method": { - "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.ListDataAgents", + "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService.SetAgentOpsObservability", "service": { "fullName": "google.cloud.geminidataanalytics.v1beta.DataAgentService", "shortName": "DataAgentService" }, - "shortName": "ListDataAgents" + "shortName": "SetAgentOpsObservability" }, "parameters": [ { "name": "request", - "type": "google.cloud.geminidataanalytics_v1beta.types.ListDataAgentsRequest" + "type": "google.cloud.geminidataanalytics_v1beta.types.SetAgentOpsObservabilityRequest" }, { "name": "parent", "type": "str" }, + { + "name": "telemetry_enabled", + "type": "bool" + }, + { + "name": "data_source_type", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1283,22 +2128,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.geminidataanalytics_v1beta.services.data_agent_service.pagers.ListDataAgentsPager", - "shortName": "list_data_agents" + "resultType": "google.api_core.operation.Operation", + "shortName": "set_agent_ops_observability" }, - "description": "Sample for ListDataAgents", - "file": "geminidataanalytics_v1beta_generated_data_agent_service_list_data_agents_sync.py", + "description": "Sample for SetAgentOpsObservability", + "file": "geminidataanalytics_v1beta_generated_data_agent_service_set_agent_ops_observability_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_ListDataAgents_sync", + "regionTag": "geminidataanalytics_v1beta_generated_DataAgentService_SetAgentOpsObservability_sync", "segments": [ { - "end": 52, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 56, "start": 27, "type": "SHORT" }, @@ -1308,22 +2153,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "geminidataanalytics_v1beta_generated_data_agent_service_list_data_agents_sync.py" + "title": "geminidataanalytics_v1beta_generated_data_agent_service_set_agent_ops_observability_sync.py" }, { "canonical": true, @@ -2944,6 +3789,175 @@ } ], "title": "geminidataanalytics_v1beta_generated_data_chat_service_query_data_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.geminidataanalytics_v1beta.DataChatServiceAsyncClient", + "shortName": "DataChatServiceAsyncClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1beta.DataChatServiceAsyncClient.update_conversation", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataChatService.UpdateConversation", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataChatService", + "shortName": "DataChatService" + }, + "shortName": "UpdateConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1beta.types.UpdateConversationRequest" + }, + { + "name": "conversation", + "type": "google.cloud.geminidataanalytics_v1beta.types.Conversation" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1beta.types.Conversation", + "shortName": "update_conversation" + }, + "description": "Sample for UpdateConversation", + "file": "geminidataanalytics_v1beta_generated_data_chat_service_update_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1beta_generated_DataChatService_UpdateConversation_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1beta_generated_data_chat_service_update_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.geminidataanalytics_v1beta.DataChatServiceClient", + "shortName": "DataChatServiceClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1beta.DataChatServiceClient.update_conversation", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataChatService.UpdateConversation", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataChatService", + "shortName": "DataChatService" + }, + "shortName": "UpdateConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1beta.types.UpdateConversationRequest" + }, + { + "name": "conversation", + "type": "google.cloud.geminidataanalytics_v1beta.types.Conversation" + }, + { + "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, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1beta.types.Conversation", + "shortName": "update_conversation" + }, + "description": "Sample for UpdateConversation", + "file": "geminidataanalytics_v1beta_generated_data_chat_service_update_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1beta_generated_DataChatService_UpdateConversation_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "geminidataanalytics_v1beta_generated_data_chat_service_update_conversation_sync.py" } ] } diff --git a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1/test_data_agent_service.py b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1/test_data_agent_service.py index 2e154cc29bed..c705d1180378 100644 --- a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1/test_data_agent_service.py +++ b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1/test_data_agent_service.py @@ -2222,6 +2222,7 @@ def test_get_data_agent(request_type, transport: str = "grpc"): display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) response = client.get_data_agent(request) @@ -2237,6 +2238,7 @@ def test_get_data_agent(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" assert response.description == "description_value" assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True def test_get_data_agent_non_empty_request_with_auto_populated_field(): @@ -2372,6 +2374,7 @@ async def test_get_data_agent_async(request_type, transport: str = "grpc_asyncio display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) ) response = await client.get_data_agent(request) @@ -2388,6 +2391,7 @@ async def test_get_data_agent_async(request_type, transport: str = "grpc_asyncio assert response.display_name == "display_name_value" assert response.description == "description_value" assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True def test_get_data_agent_field_headers(): @@ -2962,6 +2966,7 @@ def test_create_data_agent_sync(request_type, transport: str = "grpc"): display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) response = client.create_data_agent_sync(request) @@ -2977,6 +2982,7 @@ def test_create_data_agent_sync(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" assert response.description == "description_value" assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True def test_create_data_agent_sync_non_empty_request_with_auto_populated_field(): @@ -3125,6 +3131,7 @@ async def test_create_data_agent_sync_async( display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) ) response = await client.create_data_agent_sync(request) @@ -3141,6 +3148,7 @@ async def test_create_data_agent_sync_async( assert response.display_name == "display_name_value" assert response.description == "description_value" assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True def test_create_data_agent_sync_field_headers(): @@ -3763,6 +3771,7 @@ def test_update_data_agent_sync(request_type, transport: str = "grpc"): display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) response = client.update_data_agent_sync(request) @@ -3778,6 +3787,7 @@ def test_update_data_agent_sync(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" assert response.description == "description_value" assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True def test_update_data_agent_sync_non_empty_request_with_auto_populated_field(): @@ -3920,6 +3930,7 @@ async def test_update_data_agent_sync_async( display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) ) response = await client.update_data_agent_sync(request) @@ -3936,6 +3947,7 @@ async def test_update_data_agent_sync_async( assert response.display_name == "display_name_value" assert response.description == "description_value" assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True def test_update_data_agent_sync_field_headers(): @@ -5495,6 +5507,758 @@ async def test_set_iam_policy_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + data_agent_service.SetAgentOpsObservabilityRequest(), + {}, + ], +) +def test_set_agent_ops_observability(request_type, transport: str = "grpc"): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.set_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = data_agent_service.SetAgentOpsObservabilityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_set_agent_ops_observability_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = data_agent_service.SetAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.set_agent_ops_observability(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.SetAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + assert args[0] == request_msg + + +def test_set_agent_ops_observability_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.set_agent_ops_observability + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.set_agent_ops_observability + ] = mock_rpc + request = {} + client.set_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.set_agent_ops_observability(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_set_agent_ops_observability_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.set_agent_ops_observability + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.set_agent_ops_observability + ] = mock_rpc + + request = {} + await client.set_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.set_agent_ops_observability(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + data_agent_service.SetAgentOpsObservabilityRequest(), + {}, + ], +) +async def test_set_agent_ops_observability_async( + request_type, transport: str = "grpc_asyncio" +): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__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.set_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = data_agent_service.SetAgentOpsObservabilityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_set_agent_ops_observability_field_headers(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_agent_service.SetAgentOpsObservabilityRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.set_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_set_agent_ops_observability_field_headers_async(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_agent_service.SetAgentOpsObservabilityRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.set_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_set_agent_ops_observability_flattened(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__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.set_agent_ops_observability( + parent="parent_value", + telemetry_enabled=True, + data_source_type="data_source_type_value", + ) + + # Establish that the 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].telemetry_enabled + mock_val = True + assert arg == mock_val + arg = args[0].data_source_type + mock_val = "data_source_type_value" + assert arg == mock_val + + +def test_set_agent_ops_observability_flattened_error(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_agent_ops_observability( + data_agent_service.SetAgentOpsObservabilityRequest(), + parent="parent_value", + telemetry_enabled=True, + data_source_type="data_source_type_value", + ) + + +@pytest.mark.asyncio +async def test_set_agent_ops_observability_flattened_async(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__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.set_agent_ops_observability( + parent="parent_value", + telemetry_enabled=True, + data_source_type="data_source_type_value", + ) + + # Establish that 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].telemetry_enabled + mock_val = True + assert arg == mock_val + arg = args[0].data_source_type + mock_val = "data_source_type_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_set_agent_ops_observability_flattened_error_async(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_agent_ops_observability( + data_agent_service.SetAgentOpsObservabilityRequest(), + parent="parent_value", + telemetry_enabled=True, + data_source_type="data_source_type_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + data_agent_service.RetrieveAgentOpsObservabilityRequest(), + {}, + ], +) +def test_retrieve_agent_ops_observability(request_type, transport: str = "grpc"): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse( + telemetry_enabled=True, + bigquery_enabled=True, + cloud_trace_enabled=True, + cloud_monitoring_enabled=True, + cloud_logging_enabled=True, + bqaa_enabled=True, + ) + response = client.retrieve_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = data_agent_service.RetrieveAgentOpsObservabilityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, data_agent_service.RetrieveAgentOpsObservabilityResponse + ) + assert response.telemetry_enabled is True + assert response.bigquery_enabled is True + assert response.cloud_trace_enabled is True + assert response.cloud_monitoring_enabled is True + assert response.cloud_logging_enabled is True + assert response.bqaa_enabled is True + + +def test_retrieve_agent_ops_observability_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = data_agent_service.RetrieveAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.retrieve_agent_ops_observability(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.RetrieveAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + assert args[0] == request_msg + + +def test_retrieve_agent_ops_observability_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.retrieve_agent_ops_observability + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.retrieve_agent_ops_observability + ] = mock_rpc + request = {} + client.retrieve_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.retrieve_agent_ops_observability(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_retrieve_agent_ops_observability_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.retrieve_agent_ops_observability + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.retrieve_agent_ops_observability + ] = mock_rpc + + request = {} + await client.retrieve_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.retrieve_agent_ops_observability(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + data_agent_service.RetrieveAgentOpsObservabilityRequest(), + {}, + ], +) +async def test_retrieve_agent_ops_observability_async( + request_type, transport: str = "grpc_asyncio" +): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_agent_service.RetrieveAgentOpsObservabilityResponse( + telemetry_enabled=True, + bigquery_enabled=True, + cloud_trace_enabled=True, + cloud_monitoring_enabled=True, + cloud_logging_enabled=True, + bqaa_enabled=True, + ) + ) + response = await client.retrieve_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = data_agent_service.RetrieveAgentOpsObservabilityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, data_agent_service.RetrieveAgentOpsObservabilityResponse + ) + assert response.telemetry_enabled is True + assert response.bigquery_enabled is True + assert response.cloud_trace_enabled is True + assert response.cloud_monitoring_enabled is True + assert response.cloud_logging_enabled is True + assert response.bqaa_enabled is True + + +def test_retrieve_agent_ops_observability_field_headers(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_agent_service.RetrieveAgentOpsObservabilityRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + call.return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() + client.retrieve_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_retrieve_agent_ops_observability_field_headers_async(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_agent_service.RetrieveAgentOpsObservabilityRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_agent_service.RetrieveAgentOpsObservabilityResponse() + ) + await client.retrieve_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_retrieve_agent_ops_observability_flattened(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.retrieve_agent_ops_observability( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Establish that the 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].data_source_type + mock_val = "data_source_type_value" + assert arg == mock_val + + +def test_retrieve_agent_ops_observability_flattened_error(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.retrieve_agent_ops_observability( + data_agent_service.RetrieveAgentOpsObservabilityRequest(), + parent="parent_value", + data_source_type="data_source_type_value", + ) + + +@pytest.mark.asyncio +async def test_retrieve_agent_ops_observability_flattened_async(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_agent_service.RetrieveAgentOpsObservabilityResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.retrieve_agent_ops_observability( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Establish that 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].data_source_type + mock_val = "data_source_type_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_retrieve_agent_ops_observability_flattened_error_async(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.retrieve_agent_ops_observability( + data_agent_service.RetrieveAgentOpsObservabilityRequest(), + parent="parent_value", + data_source_type="data_source_type_value", + ) + + def test_list_data_agents_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5509,37 +6273,540 @@ def test_list_data_agents_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_data_agents in client._transport._wrapped_methods + assert client._transport.list_data_agents in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_data_agents] = ( + mock_rpc + ) + + request = {} + client.list_data_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_agents(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_data_agents_rest_required_fields( + request_type=data_agent_service.ListDataAgentsRequest, +): + transport_class = transports.DataAgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListDataAgents, + "_BaseListDataAgents__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "creatorFilter", + "filter", + "orderBy", + "pageSize", + "pageToken", + "showDeleted", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = data_agent_service.ListDataAgentsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_agent_service.ListDataAgentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_data_agents(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_data_agents_rest_flattened(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = data_agent_service.ListDataAgentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = data_agent_service.ListDataAgentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_data_agents(**mock_args) + + # Establish that the underlying call 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/*}/dataAgents" % client.transport._host, + args[1], + ) + + +def test_list_data_agents_rest_flattened_error(transport: str = "rest"): + client = DataAgentServiceClient( + credentials=ga_credentials.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_data_agents( + data_agent_service.ListDataAgentsRequest(), + parent="parent_value", + ) + + +def test_list_data_agents_rest_pager(transport: str = "rest"): + client = DataAgentServiceClient( + 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 = ( + data_agent_service.ListDataAgentsResponse( + data_agents=[ + data_agent.DataAgent(), + data_agent.DataAgent(), + data_agent.DataAgent(), + ], + next_page_token="abc", + ), + data_agent_service.ListDataAgentsResponse( + data_agents=[], + next_page_token="def", + ), + data_agent_service.ListDataAgentsResponse( + data_agents=[ + data_agent.DataAgent(), + ], + next_page_token="ghi", + ), + data_agent_service.ListDataAgentsResponse( + data_agents=[ + data_agent.DataAgent(), + data_agent.DataAgent(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + data_agent_service.ListDataAgentsResponse.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_data_agents(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, data_agent.DataAgent) for i in results) + + pages = list(client.list_data_agents(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_accessible_data_agents_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_accessible_data_agents + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_accessible_data_agents + ] = mock_rpc + + request = {} + client.list_accessible_data_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_accessible_data_agents(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_accessible_data_agents_rest_required_fields( + request_type=data_agent_service.ListAccessibleDataAgentsRequest, +): + transport_class = transports.DataAgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListAccessibleDataAgents, + "_BaseListAccessibleDataAgents__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "creatorFilter", + "filter", + "orderBy", + "pageSize", + "pageToken", + "showDeleted", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = data_agent_service.ListAccessibleDataAgentsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_agent_service.ListAccessibleDataAgentsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_accessible_data_agents(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_accessible_data_agents_rest_flattened(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = data_agent_service.ListAccessibleDataAgentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = data_agent_service.ListAccessibleDataAgentsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_accessible_data_agents(**mock_args) + + # Establish that the underlying call 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/*}/dataAgents:listAccessible" + % client.transport._host, + args[1], + ) + + +def test_list_accessible_data_agents_rest_flattened_error(transport: str = "rest"): + client = DataAgentServiceClient( + credentials=ga_credentials.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_accessible_data_agents( + data_agent_service.ListAccessibleDataAgentsRequest(), + parent="parent_value", + ) + + +def test_list_accessible_data_agents_rest_pager(transport: str = "rest"): + client = DataAgentServiceClient( + 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 = ( + data_agent_service.ListAccessibleDataAgentsResponse( + data_agents=[ + data_agent.DataAgent(), + data_agent.DataAgent(), + data_agent.DataAgent(), + ], + next_page_token="abc", + ), + data_agent_service.ListAccessibleDataAgentsResponse( + data_agents=[], + next_page_token="def", + ), + data_agent_service.ListAccessibleDataAgentsResponse( + data_agents=[ + data_agent.DataAgent(), + ], + next_page_token="ghi", + ), + data_agent_service.ListAccessibleDataAgentsResponse( + data_agents=[ + data_agent.DataAgent(), + data_agent.DataAgent(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + data_agent_service.ListAccessibleDataAgentsResponse.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_accessible_data_agents(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, data_agent.DataAgent) for i in results) + + pages = list(client.list_accessible_data_agents(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_data_agent_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_agent in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_data_agents] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_data_agent] = mock_rpc request = {} - client.list_data_agents(request) + client.get_data_agent(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_data_agents(request) + client.get_data_agent(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_data_agents_rest_required_fields( - request_type=data_agent_service.ListDataAgentsRequest, +def test_get_data_agent_rest_required_fields( + request_type=data_agent_service.GetDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -5549,8 +6816,8 @@ def test_list_data_agents_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListDataAgents, - "_BaseListDataAgents__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetDataAgent, + "_BaseGetDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -5560,22 +6827,11 @@ def test_list_data_agents_rest_required_fields( # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - "showDeleted", - ) - ) + jsonified_request["name"] = "name_value" # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5584,7 +6840,7 @@ def test_list_data_agents_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = data_agent_service.ListDataAgentsResponse() + return_value = data_agent.DataAgent() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -5605,21 +6861,21 @@ def test_list_data_agents_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = data_agent_service.ListDataAgentsResponse.pb(return_value) + return_value = data_agent.DataAgent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_data_agents(request) + response = client.get_data_agent(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_data_agents_rest_flattened(): +def test_get_data_agent_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5628,14 +6884,16 @@ def test_list_data_agents_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = data_agent_service.ListDataAgentsResponse() + return_value = data_agent.DataAgent() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "name": "projects/sample1/locations/sample2/dataAgents/sample3" + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) @@ -5643,25 +6901,25 @@ def test_list_data_agents_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = data_agent_service.ListDataAgentsResponse.pb(return_value) + return_value = data_agent.DataAgent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_data_agents(**mock_args) + client.get_data_agent(**mock_args) # Establish that the underlying call 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/*}/dataAgents" % client.transport._host, + "%s/v1/{name=projects/*/locations/*/dataAgents/*}" % client.transport._host, args[1], ) -def test_list_data_agents_rest_flattened_error(transport: str = "rest"): +def test_get_data_agent_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5670,79 +6928,13 @@ def test_list_data_agents_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_data_agents( - data_agent_service.ListDataAgentsRequest(), - parent="parent_value", - ) - - -def test_list_data_agents_rest_pager(transport: str = "rest"): - client = DataAgentServiceClient( - 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 = ( - data_agent_service.ListDataAgentsResponse( - data_agents=[ - data_agent.DataAgent(), - data_agent.DataAgent(), - data_agent.DataAgent(), - ], - next_page_token="abc", - ), - data_agent_service.ListDataAgentsResponse( - data_agents=[], - next_page_token="def", - ), - data_agent_service.ListDataAgentsResponse( - data_agents=[ - data_agent.DataAgent(), - ], - next_page_token="ghi", - ), - data_agent_service.ListDataAgentsResponse( - data_agents=[ - data_agent.DataAgent(), - data_agent.DataAgent(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - data_agent_service.ListDataAgentsResponse.to_json(x) for x in response + client.get_data_agent( + data_agent_service.GetDataAgentRequest(), + name="name_value", ) - 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_data_agents(request=sample_request) - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, data_agent.DataAgent) for i in results) - - pages = list(client.list_data_agents(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token -def test_list_accessible_data_agents_rest_use_cached_wrapped_rpc(): +def test_create_data_agent_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5756,35 +6948,36 @@ def test_list_accessible_data_agents_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_accessible_data_agents - in client._transport._wrapped_methods - ) + assert client._transport.create_data_agent in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.list_accessible_data_agents - ] = mock_rpc + client._transport._wrapped_methods[client._transport.create_data_agent] = ( + mock_rpc + ) request = {} - client.list_accessible_data_agents(request) + client.create_data_agent(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_accessible_data_agents(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_data_agent(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_accessible_data_agents_rest_required_fields( - request_type=data_agent_service.ListAccessibleDataAgentsRequest, +def test_create_data_agent_rest_required_fields( + request_type=data_agent_service.CreateDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport @@ -5799,8 +6992,8 @@ def test_list_accessible_data_agents_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListAccessibleDataAgents, - "_BaseListAccessibleDataAgents__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseCreateDataAgent, + "_BaseCreateDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -5815,12 +7008,8 @@ def test_list_accessible_data_agents_rest_required_fields( # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "creatorFilter", - "filter", - "orderBy", - "pageSize", - "pageToken", - "showDeleted", + "dataAgentId", + "requestId", ) ) @@ -5835,7 +7024,7 @@ def test_list_accessible_data_agents_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = data_agent_service.ListAccessibleDataAgentsResponse() + 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 @@ -5847,32 +7036,28 @@ def test_list_accessible_data_agents_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = data_agent_service.ListAccessibleDataAgentsResponse.pb( - return_value - ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_accessible_data_agents(request) + response = client.create_data_agent(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_accessible_data_agents_rest_flattened(): +def test_create_data_agent_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5881,7 +7066,7 @@ def test_list_accessible_data_agents_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = data_agent_service.ListAccessibleDataAgentsResponse() + 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"} @@ -5889,35 +7074,38 @@ def test_list_accessible_data_agents_rest_flattened(): # get truthy value for each flattened field mock_args = dict( parent="parent_value", + data_agent=gcg_data_agent.DataAgent( + data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( + staging_context=context.Context( + system_instruction="system_instruction_value" + ) + ) + ), + data_agent_id="data_agent_id_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = data_agent_service.ListAccessibleDataAgentsResponse.pb( - return_value - ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_accessible_data_agents(**mock_args) + client.create_data_agent(**mock_args) # Establish that the underlying call 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/*}/dataAgents:listAccessible" - % client.transport._host, + "%s/v1/{parent=projects/*/locations/*}/dataAgents" % client.transport._host, args[1], ) -def test_list_accessible_data_agents_rest_flattened_error(transport: str = "rest"): +def test_create_data_agent_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5926,80 +7114,21 @@ def test_list_accessible_data_agents_rest_flattened_error(transport: str = "rest # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_accessible_data_agents( - data_agent_service.ListAccessibleDataAgentsRequest(), + client.create_data_agent( + data_agent_service.CreateDataAgentRequest(), parent="parent_value", - ) - - -def test_list_accessible_data_agents_rest_pager(transport: str = "rest"): - client = DataAgentServiceClient( - 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 = ( - data_agent_service.ListAccessibleDataAgentsResponse( - data_agents=[ - data_agent.DataAgent(), - data_agent.DataAgent(), - data_agent.DataAgent(), - ], - next_page_token="abc", - ), - data_agent_service.ListAccessibleDataAgentsResponse( - data_agents=[], - next_page_token="def", - ), - data_agent_service.ListAccessibleDataAgentsResponse( - data_agents=[ - data_agent.DataAgent(), - ], - next_page_token="ghi", - ), - data_agent_service.ListAccessibleDataAgentsResponse( - data_agents=[ - data_agent.DataAgent(), - data_agent.DataAgent(), - ], + data_agent=gcg_data_agent.DataAgent( + data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( + staging_context=context.Context( + system_instruction="system_instruction_value" + ) + ) ), + data_agent_id="data_agent_id_value", ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - data_agent_service.ListAccessibleDataAgentsResponse.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_accessible_data_agents(request=sample_request) - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, data_agent.DataAgent) for i in results) - - pages = list(client.list_accessible_data_agents(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token -def test_get_data_agent_rest_use_cached_wrapped_rpc(): +def test_create_data_agent_sync_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6013,35 +7142,40 @@ def test_get_data_agent_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_data_agent in client._transport._wrapped_methods + assert ( + client._transport.create_data_agent_sync + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_data_agent] = mock_rpc + client._transport._wrapped_methods[client._transport.create_data_agent_sync] = ( + mock_rpc + ) request = {} - client.get_data_agent(request) + client.create_data_agent_sync(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_data_agent(request) + client.create_data_agent_sync(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_data_agent_rest_required_fields( - request_type=data_agent_service.GetDataAgentRequest, +def test_create_data_agent_sync_rest_required_fields( + request_type=data_agent_service.CreateDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6051,8 +7185,8 @@ def test_get_data_agent_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetDataAgent, - "_BaseGetDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseCreateDataAgentSync, + "_BaseCreateDataAgentSync__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6062,11 +7196,19 @@ def test_get_data_agent_rest_required_fields( # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "dataAgentId", + "requestId", + ) + ) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6075,7 +7217,7 @@ def test_get_data_agent_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = data_agent.DataAgent() + return_value = gcg_data_agent.DataAgent() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -6087,30 +7229,31 @@ def test_get_data_agent_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = data_agent.DataAgent.pb(return_value) + return_value = gcg_data_agent.DataAgent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_data_agent(request) + response = client.create_data_agent_sync(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_data_agent_rest_flattened(): +def test_create_data_agent_sync_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6119,16 +7262,22 @@ def test_get_data_agent_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = data_agent.DataAgent() + return_value = gcg_data_agent.DataAgent() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/dataAgents/sample3" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + data_agent=gcg_data_agent.DataAgent( + data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( + staging_context=context.Context( + system_instruction="system_instruction_value" + ) + ) + ), + data_agent_id="data_agent_id_value", ) mock_args.update(sample_request) @@ -6136,25 +7285,26 @@ def test_get_data_agent_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = data_agent.DataAgent.pb(return_value) + return_value = gcg_data_agent.DataAgent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_data_agent(**mock_args) + client.create_data_agent_sync(**mock_args) # Establish that the underlying call 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/*/dataAgents/*}" % client.transport._host, + "%s/v1/{parent=projects/*/locations/*}/dataAgents:createSync" + % client.transport._host, args[1], ) -def test_get_data_agent_rest_flattened_error(transport: str = "rest"): +def test_create_data_agent_sync_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6163,13 +7313,21 @@ def test_get_data_agent_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_data_agent( - data_agent_service.GetDataAgentRequest(), - name="name_value", + client.create_data_agent_sync( + data_agent_service.CreateDataAgentRequest(), + parent="parent_value", + data_agent=gcg_data_agent.DataAgent( + data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( + staging_context=context.Context( + system_instruction="system_instruction_value" + ) + ) + ), + data_agent_id="data_agent_id_value", ) -def test_create_data_agent_rest_use_cached_wrapped_rpc(): +def test_update_data_agent_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6183,19 +7341,19 @@ def test_create_data_agent_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_data_agent in client._transport._wrapped_methods + assert client._transport.update_data_agent in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_data_agent] = ( + client._transport._wrapped_methods[client._transport.update_data_agent] = ( mock_rpc ) request = {} - client.create_data_agent(request) + client.update_data_agent(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6204,20 +7362,19 @@ def test_create_data_agent_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_data_agent(request) + client.update_data_agent(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_data_agent_rest_required_fields( - request_type=data_agent_service.CreateDataAgentRequest, +def test_update_data_agent_rest_required_fields( + request_type=data_agent_service.UpdateDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6227,8 +7384,8 @@ def test_create_data_agent_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseCreateDataAgent, - "_BaseCreateDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseUpdateDataAgent, + "_BaseUpdateDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6238,19 +7395,15 @@ def test_create_data_agent_rest_required_fields( # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "dataAgentId", "requestId", + "updateMask", ) ) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6271,7 +7424,7 @@ def test_create_data_agent_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -6285,14 +7438,14 @@ def test_create_data_agent_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_data_agent(request) + response = client.update_data_agent(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_data_agent_rest_flattened(): +def test_update_data_agent_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6304,11 +7457,14 @@ def test_create_data_agent_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "data_agent": { + "name": "projects/sample1/locations/sample2/dataAgents/sample3" + } + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", data_agent=gcg_data_agent.DataAgent( data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( staging_context=context.Context( @@ -6316,7 +7472,7 @@ def test_create_data_agent_rest_flattened(): ) ) ), - data_agent_id="data_agent_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -6328,19 +7484,20 @@ def test_create_data_agent_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_data_agent(**mock_args) + client.update_data_agent(**mock_args) # Establish that the underlying call 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/*}/dataAgents" % client.transport._host, + "%s/v1/{data_agent.name=projects/*/locations/*/dataAgents/*}" + % client.transport._host, args[1], ) -def test_create_data_agent_rest_flattened_error(transport: str = "rest"): +def test_update_data_agent_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6349,9 +7506,8 @@ def test_create_data_agent_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_data_agent( - data_agent_service.CreateDataAgentRequest(), - parent="parent_value", + client.update_data_agent( + data_agent_service.UpdateDataAgentRequest(), data_agent=gcg_data_agent.DataAgent( data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( staging_context=context.Context( @@ -6359,11 +7515,11 @@ def test_create_data_agent_rest_flattened_error(transport: str = "rest"): ) ) ), - data_agent_id="data_agent_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_create_data_agent_sync_rest_use_cached_wrapped_rpc(): +def test_update_data_agent_sync_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6378,7 +7534,7 @@ def test_create_data_agent_sync_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_data_agent_sync + client._transport.update_data_agent_sync in client._transport._wrapped_methods ) @@ -6387,30 +7543,29 @@ def test_create_data_agent_sync_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_data_agent_sync] = ( + client._transport._wrapped_methods[client._transport.update_data_agent_sync] = ( mock_rpc ) request = {} - client.create_data_agent_sync(request) + client.update_data_agent_sync(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_data_agent_sync(request) + client.update_data_agent_sync(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_data_agent_sync_rest_required_fields( - request_type=data_agent_service.CreateDataAgentRequest, +def test_update_data_agent_sync_rest_required_fields( + request_type=data_agent_service.UpdateDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6420,8 +7575,8 @@ def test_create_data_agent_sync_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseCreateDataAgentSync, - "_BaseCreateDataAgentSync__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseUpdateDataAgentSync, + "_BaseUpdateDataAgentSync__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6431,19 +7586,15 @@ def test_create_data_agent_sync_rest_required_fields( # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "dataAgentId", "requestId", + "updateMask", ) ) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6464,7 +7615,7 @@ def test_create_data_agent_sync_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -6481,14 +7632,14 @@ def test_create_data_agent_sync_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_data_agent_sync(request) + response = client.update_data_agent_sync(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_data_agent_sync_rest_flattened(): +def test_update_data_agent_sync_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6500,11 +7651,14 @@ def test_create_data_agent_sync_rest_flattened(): return_value = gcg_data_agent.DataAgent() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "data_agent": { + "name": "projects/sample1/locations/sample2/dataAgents/sample3" + } + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", data_agent=gcg_data_agent.DataAgent( data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( staging_context=context.Context( @@ -6512,7 +7666,7 @@ def test_create_data_agent_sync_rest_flattened(): ) ) ), - data_agent_id="data_agent_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -6526,20 +7680,20 @@ def test_create_data_agent_sync_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_data_agent_sync(**mock_args) + client.update_data_agent_sync(**mock_args) # Establish that the underlying call 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/*}/dataAgents:createSync" + "%s/v1/{data_agent.name=projects/*/locations/*/dataAgents/*}:updateSync" % client.transport._host, args[1], ) -def test_create_data_agent_sync_rest_flattened_error(transport: str = "rest"): +def test_update_data_agent_sync_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6548,9 +7702,8 @@ def test_create_data_agent_sync_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_data_agent_sync( - data_agent_service.CreateDataAgentRequest(), - parent="parent_value", + client.update_data_agent_sync( + data_agent_service.UpdateDataAgentRequest(), data_agent=gcg_data_agent.DataAgent( data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( staging_context=context.Context( @@ -6558,11 +7711,11 @@ def test_create_data_agent_sync_rest_flattened_error(transport: str = "rest"): ) ) ), - data_agent_id="data_agent_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_update_data_agent_rest_use_cached_wrapped_rpc(): +def test_delete_data_agent_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6576,19 +7729,19 @@ def test_update_data_agent_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_data_agent in client._transport._wrapped_methods + assert client._transport.delete_data_agent in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_data_agent] = ( + client._transport._wrapped_methods[client._transport.delete_data_agent] = ( mock_rpc ) request = {} - client.update_data_agent(request) + client.delete_data_agent(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6597,19 +7750,20 @@ def test_update_data_agent_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_data_agent(request) + client.delete_data_agent(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_data_agent_rest_required_fields( - request_type=data_agent_service.UpdateDataAgentRequest, +def test_delete_data_agent_rest_required_fields( + request_type=data_agent_service.DeleteDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6619,8 +7773,8 @@ def test_update_data_agent_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseUpdateDataAgent, - "_BaseUpdateDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseDeleteDataAgent, + "_BaseDeleteDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6630,15 +7784,14 @@ def test_update_data_agent_rest_required_fields( # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "requestId", - "updateMask", - ) - ) + assert not set(unset_fields) - set(("requestId",)) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6659,10 +7812,9 @@ def test_update_data_agent_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -6673,14 +7825,14 @@ def test_update_data_agent_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_data_agent(request) + response = client.delete_data_agent(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_data_agent_rest_flattened(): +def test_delete_data_agent_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6693,21 +7845,12 @@ def test_update_data_agent_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "data_agent": { - "name": "projects/sample1/locations/sample2/dataAgents/sample3" - } + "name": "projects/sample1/locations/sample2/dataAgents/sample3" } # get truthy value for each flattened field mock_args = dict( - data_agent=gcg_data_agent.DataAgent( - data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( - staging_context=context.Context( - system_instruction="system_instruction_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -6719,20 +7862,19 @@ def test_update_data_agent_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_data_agent(**mock_args) + client.delete_data_agent(**mock_args) # Establish that the underlying call 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/{data_agent.name=projects/*/locations/*/dataAgents/*}" - % client.transport._host, + "%s/v1/{name=projects/*/locations/*/dataAgents/*}" % client.transport._host, args[1], ) -def test_update_data_agent_rest_flattened_error(transport: str = "rest"): +def test_delete_data_agent_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6741,20 +7883,13 @@ def test_update_data_agent_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_data_agent( - data_agent_service.UpdateDataAgentRequest(), - data_agent=gcg_data_agent.DataAgent( - data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( - staging_context=context.Context( - system_instruction="system_instruction_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_data_agent( + data_agent_service.DeleteDataAgentRequest(), + name="name_value", ) -def test_update_data_agent_sync_rest_use_cached_wrapped_rpc(): +def test_delete_data_agent_sync_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6769,7 +7904,7 @@ def test_update_data_agent_sync_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_data_agent_sync + client._transport.delete_data_agent_sync in client._transport._wrapped_methods ) @@ -6778,29 +7913,30 @@ def test_update_data_agent_sync_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_data_agent_sync] = ( + client._transport._wrapped_methods[client._transport.delete_data_agent_sync] = ( mock_rpc ) request = {} - client.update_data_agent_sync(request) + client.delete_data_agent_sync(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_data_agent_sync(request) + client.delete_data_agent_sync(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_data_agent_sync_rest_required_fields( - request_type=data_agent_service.UpdateDataAgentRequest, +def test_delete_data_agent_sync_rest_required_fields( + request_type=data_agent_service.DeleteDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6810,8 +7946,8 @@ def test_update_data_agent_sync_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseUpdateDataAgentSync, - "_BaseUpdateDataAgentSync__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseDeleteDataAgentSync, + "_BaseDeleteDataAgentSync__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6821,15 +7957,14 @@ def test_update_data_agent_sync_rest_required_fields( # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "requestId", - "updateMask", - ) - ) + assert not set(unset_fields) - set(("requestId",)) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6838,7 +7973,7 @@ def test_update_data_agent_sync_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gcg_data_agent.DataAgent() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -6850,31 +7985,27 @@ def test_update_data_agent_sync_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gcg_data_agent.DataAgent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_data_agent_sync(request) + response = client.delete_data_agent_sync(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_data_agent_sync_rest_flattened(): +def test_delete_data_agent_sync_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6883,52 +8014,41 @@ def test_update_data_agent_sync_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gcg_data_agent.DataAgent() + return_value = None # get arguments that satisfy an http rule for this method sample_request = { - "data_agent": { - "name": "projects/sample1/locations/sample2/dataAgents/sample3" - } + "name": "projects/sample1/locations/sample2/dataAgents/sample3" } # get truthy value for each flattened field mock_args = dict( - data_agent=gcg_data_agent.DataAgent( - data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( - staging_context=context.Context( - system_instruction="system_instruction_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcg_data_agent.DataAgent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_data_agent_sync(**mock_args) + client.delete_data_agent_sync(**mock_args) # Establish that the underlying call 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/{data_agent.name=projects/*/locations/*/dataAgents/*}:updateSync" + "%s/v1/{name=projects/*/locations/*/dataAgents/*}:deleteSync" % client.transport._host, args[1], ) -def test_update_data_agent_sync_rest_flattened_error(transport: str = "rest"): +def test_delete_data_agent_sync_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6937,20 +8057,13 @@ def test_update_data_agent_sync_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_data_agent_sync( - data_agent_service.UpdateDataAgentRequest(), - data_agent=gcg_data_agent.DataAgent( - data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( - staging_context=context.Context( - system_instruction="system_instruction_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_data_agent_sync( + data_agent_service.DeleteDataAgentRequest(), + name="name_value", ) -def test_delete_data_agent_rest_use_cached_wrapped_rpc(): +def test_get_iam_policy_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6964,43 +8077,37 @@ def test_delete_data_agent_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_data_agent in client._transport._wrapped_methods + assert client._transport.get_iam_policy in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_data_agent] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_iam_policy] = mock_rpc request = {} - client.delete_data_agent(request) + client.get_iam_policy(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_data_agent(request) + client.get_iam_policy(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_data_agent_rest_required_fields( - request_type=data_agent_service.DeleteDataAgentRequest, +def test_get_iam_policy_rest_required_fields( + request_type=iam_policy_pb2.GetIamPolicyRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["resource"] = "" request = request_type(**request_init) - pb_request = request_type.pb(request) + pb_request = request jsonified_request = json.loads( json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) @@ -7008,8 +8115,8 @@ def test_delete_data_agent_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseDeleteDataAgent, - "_BaseDeleteDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetIamPolicy, + "_BaseGetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7019,14 +8126,11 @@ def test_delete_data_agent_rest_required_fields( # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("requestId",)) + jsonified_request["resource"] = "resource_value" # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7035,7 +8139,7 @@ def test_delete_data_agent_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = policy_pb2.Policy() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7044,30 +8148,32 @@ def test_delete_data_agent_rest_required_fields( with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. - pb_request = request_type.pb(request) + pb_request = request transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "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 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_data_agent(request) + response = client.get_iam_policy(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_data_agent_rest_flattened(): +def test_get_iam_policy_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7076,16 +8182,16 @@ def test_delete_data_agent_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = policy_pb2.Policy() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/dataAgents/sample3" + "resource": "projects/sample1/locations/sample2/dataAgents/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + resource="resource_value", ) mock_args.update(sample_request) @@ -7097,19 +8203,20 @@ def test_delete_data_agent_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_data_agent(**mock_args) + client.get_iam_policy(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/dataAgents/*}" % client.transport._host, + "%s/v1/{resource=projects/*/locations/*/dataAgents/*}:getIamPolicy" + % client.transport._host, args[1], ) -def test_delete_data_agent_rest_flattened_error(transport: str = "rest"): +def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7118,13 +8225,13 @@ def test_delete_data_agent_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_data_agent( - data_agent_service.DeleteDataAgentRequest(), - name="name_value", + client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource="resource_value", ) -def test_delete_data_agent_sync_rest_use_cached_wrapped_rpc(): +def test_set_iam_policy_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7138,42 +8245,37 @@ def test_delete_data_agent_sync_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_data_agent_sync - in client._transport._wrapped_methods - ) + assert client._transport.set_iam_policy in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_data_agent_sync] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.set_iam_policy] = mock_rpc request = {} - client.delete_data_agent_sync(request) + client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_data_agent_sync(request) + client.set_iam_policy(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_data_agent_sync_rest_required_fields( - request_type=data_agent_service.DeleteDataAgentRequest, +def test_set_iam_policy_rest_required_fields( + request_type=iam_policy_pb2.SetIamPolicyRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["resource"] = "" request = request_type(**request_init) - pb_request = request_type.pb(request) + pb_request = request jsonified_request = json.loads( json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) @@ -7181,8 +8283,8 @@ def test_delete_data_agent_sync_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseDeleteDataAgentSync, - "_BaseDeleteDataAgentSync__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseSetIamPolicy, + "_BaseSetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7192,14 +8294,11 @@ def test_delete_data_agent_sync_rest_required_fields( # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("requestId",)) + jsonified_request["resource"] = "resource_value" # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7208,7 +8307,7 @@ def test_delete_data_agent_sync_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = policy_pb2.Policy() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7217,30 +8316,32 @@ def test_delete_data_agent_sync_rest_required_fields( with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. - pb_request = request_type.pb(request) + pb_request = request transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "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_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_data_agent_sync(request) + response = client.set_iam_policy(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_data_agent_sync_rest_flattened(): +def test_set_iam_policy_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7249,41 +8350,41 @@ def test_delete_data_agent_sync_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = policy_pb2.Policy() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/dataAgents/sample3" + "resource": "projects/sample1/locations/sample2/dataAgents/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + resource="resource_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_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_data_agent_sync(**mock_args) + client.set_iam_policy(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/dataAgents/*}:deleteSync" + "%s/v1/{resource=projects/*/locations/*/dataAgents/*}:setIamPolicy" % client.transport._host, args[1], ) -def test_delete_data_agent_sync_rest_flattened_error(transport: str = "rest"): +def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7292,13 +8393,13 @@ def test_delete_data_agent_sync_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_data_agent_sync( - data_agent_service.DeleteDataAgentRequest(), - name="name_value", + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource="resource_value", ) -def test_get_iam_policy_rest_use_cached_wrapped_rpc(): +def test_set_agent_ops_observability_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7312,37 +8413,47 @@ def test_get_iam_policy_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_iam_policy in client._transport._wrapped_methods + assert ( + client._transport.set_agent_ops_observability + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_iam_policy] = mock_rpc + client._transport._wrapped_methods[ + client._transport.set_agent_ops_observability + ] = mock_rpc request = {} - client.get_iam_policy(request) + client.set_agent_ops_observability(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_iam_policy(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.set_agent_ops_observability(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_iam_policy_rest_required_fields( - request_type=iam_policy_pb2.GetIamPolicyRequest, +def test_set_agent_ops_observability_rest_required_fields( + request_type=data_agent_service.SetAgentOpsObservabilityRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["resource"] = "" + request_init["parent"] = "" + request_init["data_source_type"] = "" request = request_type(**request_init) - pb_request = request + pb_request = request_type.pb(request) jsonified_request = json.loads( json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) @@ -7350,8 +8461,8 @@ def test_get_iam_policy_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetIamPolicy, - "_BaseGetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseSetAgentOpsObservability, + "_BaseSetAgentOpsObservability__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7361,11 +8472,14 @@ def test_get_iam_policy_rest_required_fields( # verify required fields with default values are now present - jsonified_request["resource"] = "resource_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["dataSourceType"] = "data_source_type_value" # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == "resource_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "dataSourceType" in jsonified_request + assert jsonified_request["dataSourceType"] == "data_source_type_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7374,7 +8488,7 @@ def test_get_iam_policy_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() + 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 @@ -7383,7 +8497,7 @@ def test_get_iam_policy_rest_required_fields( with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. - pb_request = request + pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", "method": "post", @@ -7394,21 +8508,20 @@ def test_get_iam_policy_rest_required_fields( response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_iam_policy(request) + response = client.set_agent_ops_observability(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_iam_policy_rest_flattened(): +def test_set_agent_ops_observability_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7417,16 +8530,16 @@ def test_get_iam_policy_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = { - "resource": "projects/sample1/locations/sample2/dataAgents/sample3" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - resource="resource_value", + parent="parent_value", + telemetry_enabled=True, + data_source_type="data_source_type_value", ) mock_args.update(sample_request) @@ -7438,20 +8551,20 @@ def test_get_iam_policy_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_iam_policy(**mock_args) + client.set_agent_ops_observability(**mock_args) # Establish that the underlying call 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/{resource=projects/*/locations/*/dataAgents/*}:getIamPolicy" + "%s/v1/{parent=projects/*/locations/*}/observabilitySettings:setAgentOpsObservability" % client.transport._host, args[1], ) -def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): +def test_set_agent_ops_observability_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7460,13 +8573,15 @@ def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource="resource_value", + client.set_agent_ops_observability( + data_agent_service.SetAgentOpsObservabilityRequest(), + parent="parent_value", + telemetry_enabled=True, + data_source_type="data_source_type_value", ) -def test_set_iam_policy_rest_use_cached_wrapped_rpc(): +def test_retrieve_agent_ops_observability_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7480,46 +8595,53 @@ def test_set_iam_policy_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.set_iam_policy in client._transport._wrapped_methods + assert ( + client._transport.retrieve_agent_ops_observability + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.set_iam_policy] = mock_rpc + client._transport._wrapped_methods[ + client._transport.retrieve_agent_ops_observability + ] = mock_rpc request = {} - client.set_iam_policy(request) + client.retrieve_agent_ops_observability(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.set_iam_policy(request) + client.retrieve_agent_ops_observability(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_set_iam_policy_rest_required_fields( - request_type=iam_policy_pb2.SetIamPolicyRequest, +def test_retrieve_agent_ops_observability_rest_required_fields( + request_type=data_agent_service.RetrieveAgentOpsObservabilityRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["resource"] = "" + request_init["parent"] = "" + request_init["data_source_type"] = "" request = request_type(**request_init) - pb_request = request + pb_request = request_type.pb(request) jsonified_request = json.loads( json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) # verify fields with default values are dropped + assert "dataSourceType" not in jsonified_request default_values = getattr( - transport_class._BaseSetIamPolicy, - "_BaseSetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseRetrieveAgentOpsObservability, + "_BaseRetrieveAgentOpsObservability__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7528,12 +8650,20 @@ def test_set_iam_policy_rest_required_fields( jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "dataSourceType" in jsonified_request + assert jsonified_request["dataSourceType"] == request_init["data_source_type"] - jsonified_request["resource"] = "resource_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["dataSourceType"] = "data_source_type_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("dataSourceType",)) # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == "resource_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "dataSourceType" in jsonified_request + assert jsonified_request["dataSourceType"] == "data_source_type_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7542,7 +8672,7 @@ def test_set_iam_policy_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7551,32 +8681,41 @@ def test_set_iam_policy_rest_required_fields( with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. - pb_request = request + pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.set_iam_policy(request) + response = client.retrieve_agent_ops_observability(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "dataSourceType", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_set_iam_policy_rest_flattened(): +def test_retrieve_agent_ops_observability_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7585,41 +8724,44 @@ def test_set_iam_policy_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "resource": "projects/sample1/locations/sample2/dataAgents/sample3" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - resource="resource_value", + parent="parent_value", + data_source_type="data_source_type_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.set_iam_policy(**mock_args) + client.retrieve_agent_ops_observability(**mock_args) # Establish that the underlying call 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/{resource=projects/*/locations/*/dataAgents/*}:setIamPolicy" + "%s/v1/{parent=projects/*/locations/*}:retrieveAgentOpsObservability" % client.transport._host, args[1], ) -def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): +def test_retrieve_agent_ops_observability_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7628,9 +8770,10 @@ def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource="resource_value", + client.retrieve_agent_ops_observability( + data_agent_service.RetrieveAgentOpsObservabilityRequest(), + parent="parent_value", + data_source_type="data_source_type_value", ) @@ -7974,6 +9117,50 @@ def test_set_iam_policy_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_agent_ops_observability_empty_call_grpc(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.set_agent_ops_observability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.SetAgentOpsObservabilityRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_retrieve_agent_ops_observability_empty_call_grpc(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + call.return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() + client.retrieve_agent_ops_observability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.RetrieveAgentOpsObservabilityRequest() + assert args[0] == request_msg + + def test_transport_kind_grpc_asyncio(): transport = DataAgentServiceAsyncClient.get_transport_class("grpc_asyncio")( credentials=async_anonymous_credentials() @@ -8062,6 +9249,7 @@ async def test_get_data_agent_empty_call_grpc_asyncio(): display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) ) await client.get_data_agent(request=None) @@ -8119,6 +9307,7 @@ async def test_create_data_agent_sync_empty_call_grpc_asyncio(): display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) ) await client.create_data_agent_sync(request=None) @@ -8176,6 +9365,7 @@ async def test_update_data_agent_sync_empty_call_grpc_asyncio(): display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) ) await client.update_data_agent_sync(request=None) @@ -8291,6 +9481,65 @@ async def test_set_iam_policy_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_set_agent_ops_observability_empty_call_grpc_asyncio(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.set_agent_ops_observability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.SetAgentOpsObservabilityRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_retrieve_agent_ops_observability_empty_call_grpc_asyncio(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_agent_service.RetrieveAgentOpsObservabilityResponse( + telemetry_enabled=True, + bigquery_enabled=True, + cloud_trace_enabled=True, + cloud_monitoring_enabled=True, + cloud_logging_enabled=True, + bqaa_enabled=True, + ) + ) + await client.retrieve_agent_ops_observability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.RetrieveAgentOpsObservabilityRequest() + assert args[0] == request_msg + + def test_transport_kind_rest(): transport = DataAgentServiceClient.get_transport_class("rest")( credentials=ga_credentials.AnonymousCredentials() @@ -8628,6 +9877,7 @@ def test_get_data_agent_rest_call_success(request_type): display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) # Wrap the value into a proper Response obj @@ -8648,6 +9898,7 @@ def test_get_data_agent_rest_call_success(request_type): assert response.display_name == "display_name_value" assert response.description == "description_value" assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -8857,6 +10108,25 @@ def test_create_data_agent_rest_call_success(request_type): ], "sorts": ["sorts_value1", "sorts_value2"], "limit": "limit_value", + "dynamic_fields": [ + { + "category": "category_value", + "name": "name_value", + "label": "label_value", + "based_on": "based_on_value", + "type_": "type__value", + "description": "description_value", + "expression": "expression_value", + "filter_expression": "filter_expression_value", + "value_format": "value_format_value", + "value_format_name": "value_format_name_value", + "calculation_type": "calculation_type_value", + "args": ["args_value1", "args_value2"], + "kind_hint": "kind_hint_value", + "type_hint": "type_hint_value", + "is_disabled": True, + } + ], "query_id": "query_id_value", "client_id": "client_id_value", }, @@ -8905,6 +10175,8 @@ def test_create_data_agent_rest_call_success(request_type): "delete_time": {}, "purge_time": {}, "kms_key": "kms_key_value", + "bigquery_agent_analytics_enabled": True, + "bigquery_agent_analytics_table": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -9201,6 +10473,25 @@ def test_create_data_agent_sync_rest_call_success(request_type): ], "sorts": ["sorts_value1", "sorts_value2"], "limit": "limit_value", + "dynamic_fields": [ + { + "category": "category_value", + "name": "name_value", + "label": "label_value", + "based_on": "based_on_value", + "type_": "type__value", + "description": "description_value", + "expression": "expression_value", + "filter_expression": "filter_expression_value", + "value_format": "value_format_value", + "value_format_name": "value_format_name_value", + "calculation_type": "calculation_type_value", + "args": ["args_value1", "args_value2"], + "kind_hint": "kind_hint_value", + "type_hint": "type_hint_value", + "is_disabled": True, + } + ], "query_id": "query_id_value", "client_id": "client_id_value", }, @@ -9249,6 +10540,8 @@ def test_create_data_agent_sync_rest_call_success(request_type): "delete_time": {}, "purge_time": {}, "kms_key": "kms_key_value", + "bigquery_agent_analytics_enabled": True, + "bigquery_agent_analytics_table": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -9327,6 +10620,7 @@ def get_message_fields(field): display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) # Wrap the value into a proper Response obj @@ -9347,6 +10641,7 @@ def get_message_fields(field): assert response.display_name == "display_name_value" assert response.description == "description_value" assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -9560,6 +10855,25 @@ def test_update_data_agent_rest_call_success(request_type): ], "sorts": ["sorts_value1", "sorts_value2"], "limit": "limit_value", + "dynamic_fields": [ + { + "category": "category_value", + "name": "name_value", + "label": "label_value", + "based_on": "based_on_value", + "type_": "type__value", + "description": "description_value", + "expression": "expression_value", + "filter_expression": "filter_expression_value", + "value_format": "value_format_value", + "value_format_name": "value_format_name_value", + "calculation_type": "calculation_type_value", + "args": ["args_value1", "args_value2"], + "kind_hint": "kind_hint_value", + "type_hint": "type_hint_value", + "is_disabled": True, + } + ], "query_id": "query_id_value", "client_id": "client_id_value", }, @@ -9608,6 +10922,8 @@ def test_update_data_agent_rest_call_success(request_type): "delete_time": {}, "purge_time": {}, "kms_key": "kms_key_value", + "bigquery_agent_analytics_enabled": True, + "bigquery_agent_analytics_table": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -9908,6 +11224,25 @@ def test_update_data_agent_sync_rest_call_success(request_type): ], "sorts": ["sorts_value1", "sorts_value2"], "limit": "limit_value", + "dynamic_fields": [ + { + "category": "category_value", + "name": "name_value", + "label": "label_value", + "based_on": "based_on_value", + "type_": "type__value", + "description": "description_value", + "expression": "expression_value", + "filter_expression": "filter_expression_value", + "value_format": "value_format_value", + "value_format_name": "value_format_name_value", + "calculation_type": "calculation_type_value", + "args": ["args_value1", "args_value2"], + "kind_hint": "kind_hint_value", + "type_hint": "type_hint_value", + "is_disabled": True, + } + ], "query_id": "query_id_value", "client_id": "client_id_value", }, @@ -9956,6 +11291,8 @@ def test_update_data_agent_sync_rest_call_success(request_type): "delete_time": {}, "purge_time": {}, "kms_key": "kms_key_value", + "bigquery_agent_analytics_enabled": True, + "bigquery_agent_analytics_table": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -10034,30 +11371,283 @@ def get_message_fields(field): display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcg_data_agent.DataAgent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_data_agent_sync(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcg_data_agent.DataAgent) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_data_agent_sync_rest_interceptors(null_interceptor): + transport = transports.DataAgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DataAgentServiceRestInterceptor(), + ) + client = DataAgentServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DataAgentServiceRestInterceptor, "post_update_data_agent_sync" + ) as post, + mock.patch.object( + transports.DataAgentServiceRestInterceptor, + "post_update_data_agent_sync_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DataAgentServiceRestInterceptor, "pre_update_data_agent_sync" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = data_agent_service.UpdateDataAgentRequest.pb( + data_agent_service.UpdateDataAgentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcg_data_agent.DataAgent.to_json(gcg_data_agent.DataAgent()) + req.return_value.content = return_value + + request = data_agent_service.UpdateDataAgentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcg_data_agent.DataAgent() + post_with_metadata.return_value = gcg_data_agent.DataAgent(), metadata + + client.update_data_agent_sync( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_data_agent_rest_bad_request( + request_type=data_agent_service.DeleteDataAgentRequest, +): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/dataAgents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_data_agent(request) + + +@pytest.mark.parametrize( + "request_type", + [ + data_agent_service.DeleteDataAgentRequest, + dict, + ], +) +def test_delete_data_agent_rest_call_success(request_type): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/dataAgents/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 = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_data_agent(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_data_agent_rest_interceptors(null_interceptor): + transport = transports.DataAgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DataAgentServiceRestInterceptor(), + ) + client = DataAgentServiceClient(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.DataAgentServiceRestInterceptor, "post_delete_data_agent" + ) as post, + mock.patch.object( + transports.DataAgentServiceRestInterceptor, + "post_delete_data_agent_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DataAgentServiceRestInterceptor, "pre_delete_data_agent" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = data_agent_service.DeleteDataAgentRequest.pb( + data_agent_service.DeleteDataAgentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = data_agent_service.DeleteDataAgentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_data_agent( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_data_agent_sync_rest_bad_request( + request_type=data_agent_service.DeleteDataAgentRequest, +): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/dataAgents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_data_agent_sync(request) + + +@pytest.mark.parametrize( + "request_type", + [ + data_agent_service.DeleteDataAgentRequest, + dict, + ], +) +def test_delete_data_agent_sync_rest_call_success(request_type): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/dataAgents/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 = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gcg_data_agent.DataAgent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_data_agent_sync(request) + response = client.delete_data_agent_sync(request) # Establish that the response is the type that we expect. - assert isinstance(response, gcg_data_agent.DataAgent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.kms_key == "kms_key_value" + assert response is None @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_data_agent_sync_rest_interceptors(null_interceptor): +def test_delete_data_agent_sync_rest_interceptors(null_interceptor): transport = transports.DataAgentServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10070,21 +11660,12 @@ def test_update_data_agent_sync_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.DataAgentServiceRestInterceptor, "post_update_data_agent_sync" - ) as post, - mock.patch.object( - transports.DataAgentServiceRestInterceptor, - "post_update_data_agent_sync_with_metadata", - ) as post_with_metadata, - mock.patch.object( - transports.DataAgentServiceRestInterceptor, "pre_update_data_agent_sync" + transports.DataAgentServiceRestInterceptor, "pre_delete_data_agent_sync" ) as pre, ): pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = data_agent_service.UpdateDataAgentRequest.pb( - data_agent_service.UpdateDataAgentRequest() + pb_message = data_agent_service.DeleteDataAgentRequest.pb( + data_agent_service.DeleteDataAgentRequest() ) transcode.return_value = { "method": "post", @@ -10096,19 +11677,15 @@ def test_update_data_agent_sync_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = gcg_data_agent.DataAgent.to_json(gcg_data_agent.DataAgent()) - req.return_value.content = return_value - request = data_agent_service.UpdateDataAgentRequest() + request = data_agent_service.DeleteDataAgentRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gcg_data_agent.DataAgent() - post_with_metadata.return_value = gcg_data_agent.DataAgent(), metadata - client.update_data_agent_sync( + client.delete_data_agent_sync( request, metadata=[ ("key", "val"), @@ -10117,18 +11694,16 @@ def test_update_data_agent_sync_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() -def test_delete_data_agent_rest_bad_request( - request_type=data_agent_service.DeleteDataAgentRequest, +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, ): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/dataAgents/sample3"} + request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10144,29 +11719,32 @@ def test_delete_data_agent_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_data_agent(request) + client.get_iam_policy(request) @pytest.mark.parametrize( "request_type", [ - data_agent_service.DeleteDataAgentRequest, + iam_policy_pb2.GetIamPolicyRequest, dict, ], ) -def test_delete_data_agent_rest_call_success(request_type): +def test_get_iam_policy_rest_call_success(request_type): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/dataAgents/sample3"} + request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -10175,14 +11753,16 @@ def test_delete_data_agent_rest_call_success(request_type): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_data_agent(request) + response = client.get_iam_policy(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_data_agent_rest_interceptors(null_interceptor): +def test_get_iam_policy_rest_interceptors(null_interceptor): transport = transports.DataAgentServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10194,24 +11774,21 @@ def test_delete_data_agent_rest_interceptors(null_interceptor): 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.DataAgentServiceRestInterceptor, "post_delete_data_agent" + transports.DataAgentServiceRestInterceptor, "post_get_iam_policy" ) as post, mock.patch.object( transports.DataAgentServiceRestInterceptor, - "post_delete_data_agent_with_metadata", + "post_get_iam_policy_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DataAgentServiceRestInterceptor, "pre_delete_data_agent" + transports.DataAgentServiceRestInterceptor, "pre_get_iam_policy" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = data_agent_service.DeleteDataAgentRequest.pb( - data_agent_service.DeleteDataAgentRequest() - ) + pb_message = iam_policy_pb2.GetIamPolicyRequest() transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10222,19 +11799,19 @@ def test_delete_data_agent_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) + return_value = json_format.MessageToJson(policy_pb2.Policy()) req.return_value.content = return_value - request = data_agent_service.DeleteDataAgentRequest() + request = iam_policy_pb2.GetIamPolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + post.return_value = policy_pb2.Policy() + post_with_metadata.return_value = policy_pb2.Policy(), metadata - client.delete_data_agent( + client.get_iam_policy( request, metadata=[ ("key", "val"), @@ -10247,14 +11824,14 @@ def test_delete_data_agent_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_data_agent_sync_rest_bad_request( - request_type=data_agent_service.DeleteDataAgentRequest, +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, ): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/dataAgents/sample3"} + request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10270,45 +11847,50 @@ def test_delete_data_agent_sync_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_data_agent_sync(request) + client.set_iam_policy(request) @pytest.mark.parametrize( "request_type", [ - data_agent_service.DeleteDataAgentRequest, + iam_policy_pb2.SetIamPolicyRequest, dict, ], ) -def test_delete_data_agent_sync_rest_call_success(request_type): +def test_set_iam_policy_rest_call_success(request_type): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/dataAgents/sample3"} + request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/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 + return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" + json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_data_agent_sync(request) + response = client.set_iam_policy(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_data_agent_sync_rest_interceptors(null_interceptor): +def test_set_iam_policy_rest_interceptors(null_interceptor): transport = transports.DataAgentServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10321,13 +11903,20 @@ def test_delete_data_agent_sync_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.DataAgentServiceRestInterceptor, "pre_delete_data_agent_sync" + transports.DataAgentServiceRestInterceptor, "post_set_iam_policy" + ) as post, + mock.patch.object( + transports.DataAgentServiceRestInterceptor, + "post_set_iam_policy_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DataAgentServiceRestInterceptor, "pre_set_iam_policy" ) as pre, ): pre.assert_not_called() - pb_message = data_agent_service.DeleteDataAgentRequest.pb( - data_agent_service.DeleteDataAgentRequest() - ) + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10338,15 +11927,19 @@ def test_delete_data_agent_sync_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(policy_pb2.Policy()) + req.return_value.content = return_value - request = data_agent_service.DeleteDataAgentRequest() + request = iam_policy_pb2.SetIamPolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + post_with_metadata.return_value = policy_pb2.Policy(), metadata - client.delete_data_agent_sync( + client.set_iam_policy( request, metadata=[ ("key", "val"), @@ -10355,16 +11948,18 @@ def test_delete_data_agent_sync_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_get_iam_policy_rest_bad_request( - request_type=iam_policy_pb2.GetIamPolicyRequest, +def test_set_agent_ops_observability_rest_bad_request( + request_type=data_agent_service.SetAgentOpsObservabilityRequest, ): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} + 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. @@ -10380,32 +11975,29 @@ def test_get_iam_policy_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_iam_policy(request) + client.set_agent_ops_observability(request) @pytest.mark.parametrize( "request_type", [ - iam_policy_pb2.GetIamPolicyRequest, + data_agent_service.SetAgentOpsObservabilityRequest, dict, ], ) -def test_get_iam_policy_rest_call_success(request_type): +def test_set_agent_ops_observability_rest_call_success(request_type): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} + 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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -10414,16 +12006,14 @@ def test_get_iam_policy_rest_call_success(request_type): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_iam_policy(request) + response = client.set_agent_ops_observability(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" + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): +def test_set_agent_ops_observability_rest_interceptors(null_interceptor): transport = transports.DataAgentServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10435,21 +12025,26 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): 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.DataAgentServiceRestInterceptor, "post_get_iam_policy" + transports.DataAgentServiceRestInterceptor, + "post_set_agent_ops_observability", ) as post, mock.patch.object( transports.DataAgentServiceRestInterceptor, - "post_get_iam_policy_with_metadata", + "post_set_agent_ops_observability_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DataAgentServiceRestInterceptor, "pre_get_iam_policy" + transports.DataAgentServiceRestInterceptor, + "pre_set_agent_ops_observability", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() + pb_message = data_agent_service.SetAgentOpsObservabilityRequest.pb( + data_agent_service.SetAgentOpsObservabilityRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10460,19 +12055,19 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(policy_pb2.Policy()) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = iam_policy_pb2.GetIamPolicyRequest() + request = data_agent_service.SetAgentOpsObservabilityRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - post_with_metadata.return_value = policy_pb2.Policy(), metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.get_iam_policy( + client.set_agent_ops_observability( request, metadata=[ ("key", "val"), @@ -10485,14 +12080,14 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_set_iam_policy_rest_bad_request( - request_type=iam_policy_pb2.SetIamPolicyRequest, +def test_retrieve_agent_ops_observability_rest_bad_request( + request_type=data_agent_service.RetrieveAgentOpsObservabilityRequest, ): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} + 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. @@ -10508,50 +12103,65 @@ def test_set_iam_policy_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.set_iam_policy(request) + client.retrieve_agent_ops_observability(request) @pytest.mark.parametrize( "request_type", [ - iam_policy_pb2.SetIamPolicyRequest, + data_agent_service.RetrieveAgentOpsObservabilityRequest, dict, ], ) -def test_set_iam_policy_rest_call_success(request_type): +def test_retrieve_agent_ops_observability_rest_call_success(request_type): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} + 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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse( + telemetry_enabled=True, + bigquery_enabled=True, + cloud_trace_enabled=True, + cloud_monitoring_enabled=True, + cloud_logging_enabled=True, + bqaa_enabled=True, ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.set_iam_policy(request) + response = client.retrieve_agent_ops_observability(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" + assert isinstance( + response, data_agent_service.RetrieveAgentOpsObservabilityResponse + ) + assert response.telemetry_enabled is True + assert response.bigquery_enabled is True + assert response.cloud_trace_enabled is True + assert response.cloud_monitoring_enabled is True + assert response.cloud_logging_enabled is True + assert response.bqaa_enabled is True @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): +def test_retrieve_agent_ops_observability_rest_interceptors(null_interceptor): transport = transports.DataAgentServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10564,20 +12174,24 @@ def test_set_iam_policy_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.DataAgentServiceRestInterceptor, "post_set_iam_policy" + transports.DataAgentServiceRestInterceptor, + "post_retrieve_agent_ops_observability", ) as post, mock.patch.object( transports.DataAgentServiceRestInterceptor, - "post_set_iam_policy_with_metadata", + "post_retrieve_agent_ops_observability_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DataAgentServiceRestInterceptor, "pre_set_iam_policy" + transports.DataAgentServiceRestInterceptor, + "pre_retrieve_agent_ops_observability", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() + pb_message = data_agent_service.RetrieveAgentOpsObservabilityRequest.pb( + data_agent_service.RetrieveAgentOpsObservabilityRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10588,19 +12202,24 @@ def test_set_iam_policy_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(policy_pb2.Policy()) + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse.to_json( + data_agent_service.RetrieveAgentOpsObservabilityResponse() + ) req.return_value.content = return_value - request = iam_policy_pb2.SetIamPolicyRequest() + request = data_agent_service.RetrieveAgentOpsObservabilityRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - post_with_metadata.return_value = policy_pb2.Policy(), metadata + post.return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() + post_with_metadata.return_value = ( + data_agent_service.RetrieveAgentOpsObservabilityResponse(), + metadata, + ) - client.set_iam_policy( + client.retrieve_agent_ops_observability( request, metadata=[ ("key", "val"), @@ -11217,6 +12836,48 @@ def test_set_iam_policy_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_agent_ops_observability_empty_call_rest(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + client.set_agent_ops_observability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.SetAgentOpsObservabilityRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_retrieve_agent_ops_observability_empty_call_rest(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + client.retrieve_agent_ops_observability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.RetrieveAgentOpsObservabilityRequest() + assert args[0] == request_msg + + def test_data_agent_service_rest_lro_client(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11278,6 +12939,8 @@ def test_data_agent_service_base_transport(): "delete_data_agent_sync", "get_iam_policy", "set_iam_policy", + "set_agent_ops_observability", + "retrieve_agent_ops_observability", "get_location", "list_locations", "get_operation", @@ -11587,6 +13250,12 @@ def test_data_agent_service_client_transport_session_collision(transport_name): session1 = client1.transport.set_iam_policy._session session2 = client2.transport.set_iam_policy._session assert session1 != session2 + session1 = client1.transport.set_agent_ops_observability._session + session2 = client2.transport.set_agent_ops_observability._session + assert session1 != session2 + session1 = client1.transport.retrieve_agent_ops_observability._session + session2 = client2.transport.retrieve_agent_ops_observability._session + assert session1 != session2 def test_data_agent_service_grpc_transport_channel(): diff --git a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1/test_data_chat_service.py b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1/test_data_chat_service.py index 9b62d655e79f..3b20709e5d2a 100644 --- a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1/test_data_chat_service.py +++ b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1/test_data_chat_service.py @@ -39,6 +39,7 @@ HAS_GOOGLE_AUTH_AIO = False import google.auth +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.struct_pb2 as struct_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import google.protobuf.wrappers_pb2 as wrappers_pb2 # type: ignore @@ -1354,8 +1355,8 @@ def test_create_conversation(request_type, transport: str = "grpc"): call.return_value = gcg_conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", kms_key="kms_key_value", - memory_paused=True, ) response = client.create_conversation(request) @@ -1369,8 +1370,8 @@ def test_create_conversation(request_type, transport: str = "grpc"): assert isinstance(response, gcg_conversation.Conversation) assert response.name == "name_value" assert response.agents == ["agents_value"] + assert response.title == "title_value" assert response.kms_key == "kms_key_value" - assert response.memory_paused is True def test_create_conversation_non_empty_request_with_auto_populated_field(): @@ -1514,8 +1515,8 @@ async def test_create_conversation_async(request_type, transport: str = "grpc_as gcg_conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", kms_key="kms_key_value", - memory_paused=True, ) ) response = await client.create_conversation(request) @@ -1530,8 +1531,8 @@ async def test_create_conversation_async(request_type, transport: str = "grpc_as assert isinstance(response, gcg_conversation.Conversation) assert response.name == "name_value" assert response.agents == ["agents_value"] + assert response.title == "title_value" assert response.kms_key == "kms_key_value" - assert response.memory_paused is True def test_create_conversation_field_headers(): @@ -2035,6 +2036,366 @@ async def test_delete_conversation_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + gcg_conversation.UpdateConversationRequest(), + {}, + ], +) +def test_update_conversation(request_type, transport: str = "grpc"): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcg_conversation.Conversation( + name="name_value", + agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", + ) + response = client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcg_conversation.UpdateConversationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcg_conversation.Conversation) + assert response.name == "name_value" + assert response.agents == ["agents_value"] + assert response.title == "title_value" + assert response.kms_key == "kms_key_value" + + +def test_update_conversation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcg_conversation.UpdateConversationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_conversation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcg_conversation.UpdateConversationRequest() + assert args[0] == request_msg + + +def test_update_conversation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_conversation in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_conversation] = ( + mock_rpc + ) + request = {} + client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_conversation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_conversation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DataChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_conversation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_conversation + ] = mock_rpc + + request = {} + await client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_conversation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + gcg_conversation.UpdateConversationRequest(), + {}, + ], +) +async def test_update_conversation_async(request_type, transport: str = "grpc_asyncio"): + client = DataChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcg_conversation.Conversation( + name="name_value", + agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", + ) + ) + response = await client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcg_conversation.UpdateConversationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcg_conversation.Conversation) + assert response.name == "name_value" + assert response.agents == ["agents_value"] + assert response.title == "title_value" + assert response.kms_key == "kms_key_value" + + +def test_update_conversation_field_headers(): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcg_conversation.UpdateConversationRequest() + + request.conversation.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + call.return_value = gcg_conversation.Conversation() + client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "conversation.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_conversation_field_headers_async(): + client = DataChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcg_conversation.UpdateConversationRequest() + + request.conversation.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcg_conversation.Conversation() + ) + await client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "conversation.name=name_value", + ) in kw["metadata"] + + +def test_update_conversation_flattened(): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcg_conversation.Conversation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_conversation( + conversation=gcg_conversation.Conversation(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].conversation + mock_val = gcg_conversation.Conversation(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_conversation_flattened_error(): + client = DataChatServiceClient( + credentials=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_conversation( + gcg_conversation.UpdateConversationRequest(), + conversation=gcg_conversation.Conversation(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_conversation_flattened_async(): + client = DataChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcg_conversation.Conversation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcg_conversation.Conversation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_conversation( + conversation=gcg_conversation.Conversation(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].conversation + mock_val = gcg_conversation.Conversation(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_conversation_flattened_error_async(): + client = DataChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_conversation( + gcg_conversation.UpdateConversationRequest(), + conversation=gcg_conversation.Conversation(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + @pytest.mark.parametrize( "request_type", [ @@ -2058,8 +2419,8 @@ def test_get_conversation(request_type, transport: str = "grpc"): call.return_value = conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", kms_key="kms_key_value", - memory_paused=True, ) response = client.get_conversation(request) @@ -2073,8 +2434,8 @@ def test_get_conversation(request_type, transport: str = "grpc"): assert isinstance(response, conversation.Conversation) assert response.name == "name_value" assert response.agents == ["agents_value"] + assert response.title == "title_value" assert response.kms_key == "kms_key_value" - assert response.memory_paused is True def test_get_conversation_non_empty_request_with_auto_populated_field(): @@ -2210,8 +2571,8 @@ async def test_get_conversation_async(request_type, transport: str = "grpc_async conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", kms_key="kms_key_value", - memory_paused=True, ) ) response = await client.get_conversation(request) @@ -2226,8 +2587,8 @@ async def test_get_conversation_async(request_type, transport: str = "grpc_async assert isinstance(response, conversation.Conversation) assert response.name == "name_value" assert response.agents == ["agents_value"] + assert response.title == "title_value" assert response.kms_key == "kms_key_value" - assert response.memory_paused is True def test_get_conversation_field_headers(): @@ -3914,6 +4275,189 @@ def test_delete_conversation_rest_flattened_error(transport: str = "rest"): ) +def test_update_conversation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_conversation in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_conversation] = ( + mock_rpc + ) + + request = {} + client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_conversation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_conversation_rest_required_fields( + request_type=gcg_conversation.UpdateConversationRequest, +): + transport_class = transports.DataChatServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateConversation, + "_BaseUpdateConversation__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcg_conversation.Conversation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcg_conversation.Conversation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_conversation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_conversation_rest_flattened(): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcg_conversation.Conversation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "conversation": { + "name": "projects/sample1/locations/sample2/conversations/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + conversation=gcg_conversation.Conversation(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcg_conversation.Conversation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_conversation(**mock_args) + + # Establish that the underlying call 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/{conversation.name=projects/*/locations/*/conversations/*}" + % client.transport._host, + args[1], + ) + + +def test_update_conversation_rest_flattened_error(transport: str = "rest"): + client = DataChatServiceClient( + credentials=ga_credentials.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_conversation( + gcg_conversation.UpdateConversationRequest(), + conversation=gcg_conversation.Conversation(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + def test_get_conversation_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4727,13 +5271,35 @@ def test_create_conversation_empty_call_grpc(): # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = gcg_conversation.CreateConversationRequest() + request_msg = gcg_conversation.CreateConversationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_conversation_empty_call_grpc(): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), "__call__" + ) as call: + call.return_value = None + client.delete_conversation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversation.DeleteConversationRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_delete_conversation_empty_call_grpc(): +def test_update_conversation_empty_call_grpc(): client = DataChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", @@ -4741,15 +5307,15 @@ def test_delete_conversation_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_conversation), "__call__" + type(client.transport.update_conversation), "__call__" ) as call: - call.return_value = None - client.delete_conversation(request=None) + call.return_value = gcg_conversation.Conversation() + client.update_conversation(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = conversation.DeleteConversationRequest() + request_msg = gcg_conversation.UpdateConversationRequest() assert args[0] == request_msg @@ -4872,8 +5438,8 @@ async def test_create_conversation_empty_call_grpc_asyncio(): gcg_conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", kms_key="kms_key_value", - memory_paused=True, ) ) await client.create_conversation(request=None) @@ -4909,6 +5475,37 @@ async def test_delete_conversation_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_conversation_empty_call_grpc_asyncio(): + client = DataChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcg_conversation.Conversation( + name="name_value", + agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", + ) + ) + await client.update_conversation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcg_conversation.UpdateConversationRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio @@ -4925,8 +5522,8 @@ async def test_get_conversation_empty_call_grpc_asyncio(): conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", kms_key="kms_key_value", - memory_paused=True, ) ) await client.get_conversation(request=None) @@ -5173,8 +5770,8 @@ def test_create_conversation_rest_call_success(request_type): "create_time": {"seconds": 751, "nanos": 543}, "last_used_time": {}, "labels": {}, + "title": "title_value", "kms_key": "kms_key_value", - "memory_paused": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -5251,8 +5848,8 @@ def get_message_fields(field): return_value = gcg_conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", kms_key="kms_key_value", - memory_paused=True, ) # Wrap the value into a proper Response obj @@ -5271,8 +5868,8 @@ def get_message_fields(field): assert isinstance(response, gcg_conversation.Conversation) assert response.name == "name_value" assert response.agents == ["agents_value"] + assert response.title == "title_value" assert response.kms_key == "kms_key_value" - assert response.memory_paused is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -5452,6 +6049,229 @@ def test_delete_conversation_rest_interceptors(null_interceptor): pre.assert_called_once() +def test_update_conversation_rest_bad_request( + request_type=gcg_conversation.UpdateConversationRequest, +): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "conversation": { + "name": "projects/sample1/locations/sample2/conversations/sample3" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_conversation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcg_conversation.UpdateConversationRequest, + dict, + ], +) +def test_update_conversation_rest_call_success(request_type): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "conversation": { + "name": "projects/sample1/locations/sample2/conversations/sample3" + } + } + request_init["conversation"] = { + "name": "projects/sample1/locations/sample2/conversations/sample3", + "agents": ["agents_value1", "agents_value2"], + "create_time": {"seconds": 751, "nanos": 543}, + "last_used_time": {}, + "labels": {}, + "title": "title_value", + "kms_key": "kms_key_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcg_conversation.UpdateConversationRequest.meta.fields["conversation"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["conversation"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["conversation"][field])): + del request_init["conversation"][field][i][subfield] + else: + del request_init["conversation"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcg_conversation.Conversation( + name="name_value", + agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcg_conversation.Conversation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_conversation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcg_conversation.Conversation) + assert response.name == "name_value" + assert response.agents == ["agents_value"] + assert response.title == "title_value" + assert response.kms_key == "kms_key_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_conversation_rest_interceptors(null_interceptor): + transport = transports.DataChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DataChatServiceRestInterceptor(), + ) + client = DataChatServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DataChatServiceRestInterceptor, "post_update_conversation" + ) as post, + mock.patch.object( + transports.DataChatServiceRestInterceptor, + "post_update_conversation_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DataChatServiceRestInterceptor, "pre_update_conversation" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcg_conversation.UpdateConversationRequest.pb( + gcg_conversation.UpdateConversationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcg_conversation.Conversation.to_json( + gcg_conversation.Conversation() + ) + req.return_value.content = return_value + + request = gcg_conversation.UpdateConversationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcg_conversation.Conversation() + post_with_metadata.return_value = gcg_conversation.Conversation(), metadata + + client.update_conversation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_get_conversation_rest_bad_request( request_type=conversation.GetConversationRequest, ): @@ -5500,8 +6320,8 @@ def test_get_conversation_rest_call_success(request_type): return_value = conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", kms_key="kms_key_value", - memory_paused=True, ) # Wrap the value into a proper Response obj @@ -5520,8 +6340,8 @@ def test_get_conversation_rest_call_success(request_type): assert isinstance(response, conversation.Conversation) assert response.name == "name_value" assert response.agents == ["agents_value"] + assert response.title == "title_value" assert response.kms_key == "kms_key_value" - assert response.memory_paused is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -6307,6 +7127,27 @@ def test_delete_conversation_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_conversation_empty_call_rest(): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + client.update_conversation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcg_conversation.UpdateConversationRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_get_conversation_empty_call_rest(): @@ -6402,6 +7243,7 @@ def test_data_chat_service_base_transport(): "chat", "create_conversation", "delete_conversation", + "update_conversation", "get_conversation", "list_conversations", "list_messages", @@ -6685,6 +7527,9 @@ def test_data_chat_service_client_transport_session_collision(transport_name): session1 = client1.transport.delete_conversation._session session2 = client2.transport.delete_conversation._session assert session1 != session2 + session1 = client1.transport.update_conversation._session + session2 = client2.transport.update_conversation._session + assert session1 != session2 session1 = client1.transport.get_conversation._session session2 = client2.transport.get_conversation._session assert session1 != session2 diff --git a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_a2a_service.py b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_a2a_service.py new file mode 100644 index 000000000000..aac1150d2a53 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_a2a_service.py @@ -0,0 +1,5389 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.auth +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account + +from google.cloud.geminidataanalytics_v1alpha.services.data_a2a_service import ( + DataA2AServiceAsyncClient, + DataA2AServiceClient, + transports, +) +from google.cloud.geminidataanalytics_v1alpha.types import data_a2a_service + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +@pytest.fixture(autouse=True) +def disable_mtls_env(): + with mock.patch.dict( + os.environ, + { + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", + "CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE": "false", + }, + ): + yield + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert DataA2AServiceClient._get_client_cert_source(None, False) is None + assert ( + DataA2AServiceClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + DataA2AServiceClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + DataA2AServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + DataA2AServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = DataA2AServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = DataA2AServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (DataA2AServiceClient, "grpc"), + (DataA2AServiceAsyncClient, "grpc_asyncio"), + (DataA2AServiceClient, "rest"), + ], +) +def test_data_a2a_service_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "geminidataanalytics.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://geminidataanalytics.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.DataA2AServiceGrpcTransport, "grpc"), + (transports.DataA2AServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DataA2AServiceRestTransport, "rest"), + ], +) +def test_data_a2a_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (DataA2AServiceClient, "grpc"), + (DataA2AServiceAsyncClient, "grpc_asyncio"), + (DataA2AServiceClient, "rest"), + ], +) +def test_data_a2a_service_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "geminidataanalytics.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://geminidataanalytics.googleapis.com" + ) + + +def test_data_a2a_service_client_get_transport_class(): + transport = DataA2AServiceClient.get_transport_class() + available_transports = [ + transports.DataA2AServiceGrpcTransport, + transports.DataA2AServiceRestTransport, + ] + assert transport in available_transports + + transport = DataA2AServiceClient.get_transport_class("grpc") + assert transport == transports.DataA2AServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (DataA2AServiceClient, transports.DataA2AServiceGrpcTransport, "grpc"), + ( + DataA2AServiceAsyncClient, + transports.DataA2AServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (DataA2AServiceClient, transports.DataA2AServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + DataA2AServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DataA2AServiceClient), +) +@mock.patch.object( + DataA2AServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DataA2AServiceAsyncClient), +) +def test_data_a2a_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(DataA2AServiceClient, "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(DataA2AServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (DataA2AServiceClient, transports.DataA2AServiceGrpcTransport, "grpc", "true"), + ( + DataA2AServiceAsyncClient, + transports.DataA2AServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (DataA2AServiceClient, transports.DataA2AServiceGrpcTransport, "grpc", "false"), + ( + DataA2AServiceAsyncClient, + transports.DataA2AServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (DataA2AServiceClient, transports.DataA2AServiceRestTransport, "rest", "true"), + (DataA2AServiceClient, transports.DataA2AServiceRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + DataA2AServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DataA2AServiceClient), +) +@mock.patch.object( + DataA2AServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DataA2AServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_data_a2a_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [DataA2AServiceClient, DataA2AServiceAsyncClient] +) +@mock.patch.object( + DataA2AServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DataA2AServiceClient), +) +@mock.patch.object( + DataA2AServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DataA2AServiceAsyncClient), +) +def test_data_a2a_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + 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 cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + 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 expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + 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 expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize( + "client_class", [DataA2AServiceClient, DataA2AServiceAsyncClient] +) +@mock.patch.object( + DataA2AServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DataA2AServiceClient), +) +@mock.patch.object( + DataA2AServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DataA2AServiceAsyncClient), +) +def test_data_a2a_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = DataA2AServiceClient._DEFAULT_UNIVERSE + default_endpoint = DataA2AServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = DataA2AServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (DataA2AServiceClient, transports.DataA2AServiceGrpcTransport, "grpc"), + ( + DataA2AServiceAsyncClient, + transports.DataA2AServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (DataA2AServiceClient, transports.DataA2AServiceRestTransport, "rest"), + ], +) +def test_data_a2a_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + DataA2AServiceClient, + transports.DataA2AServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + DataA2AServiceAsyncClient, + transports.DataA2AServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (DataA2AServiceClient, transports.DataA2AServiceRestTransport, "rest", None), + ], +) +def test_data_a2a_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_data_a2a_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.geminidataanalytics_v1alpha.services.data_a2a_service.transports.DataA2AServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = DataA2AServiceClient( + 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", + [ + ( + DataA2AServiceClient, + transports.DataA2AServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + DataA2AServiceAsyncClient, + transports.DataA2AServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_data_a2a_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "geminidataanalytics.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="geminidataanalytics.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + data_a2a_service.SendMessageRequest(), + {}, + ], +) +def test_send_message(request_type, transport: str = "grpc"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = data_a2a_service.SendMessageResponse() + response = client.send_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = data_a2a_service.SendMessageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, data_a2a_service.SendMessageResponse) + + +def test_send_message_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = data_a2a_service.SendMessageRequest( + tenant="tenant_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.send_message(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.SendMessageRequest( + tenant="tenant_value", + ) + assert args[0] == request_msg + + +def test_send_message_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.send_message in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.send_message] = mock_rpc + request = {} + client.send_message(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.send_message(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_send_message_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.send_message + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.send_message + ] = mock_rpc + + request = {} + await client.send_message(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.send_message(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + data_a2a_service.SendMessageRequest(), + {}, + ], +) +async def test_send_message_async(request_type, transport: str = "grpc_asyncio"): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_a2a_service.SendMessageResponse() + ) + response = await client.send_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = data_a2a_service.SendMessageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, data_a2a_service.SendMessageResponse) + + +def test_send_message_field_headers(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_a2a_service.SendMessageRequest() + + request.tenant = "tenant_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + call.return_value = data_a2a_service.SendMessageResponse() + client.send_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "tenant=tenant_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_send_message_field_headers_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_a2a_service.SendMessageRequest() + + request.tenant = "tenant_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_a2a_service.SendMessageResponse() + ) + await client.send_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "tenant=tenant_value", + ) in kw["metadata"] + + +def test_send_message_flattened(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = data_a2a_service.SendMessageResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.send_message( + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_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].tenant + mock_val = "tenant_value" + assert arg == mock_val + arg = args[0].message + mock_val = data_a2a_service.A2AMessage(message_id="message_id_value") + assert arg == mock_val + + +def test_send_message_flattened_error(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.send_message( + data_a2a_service.SendMessageRequest(), + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_id_value"), + ) + + +@pytest.mark.asyncio +async def test_send_message_flattened_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = data_a2a_service.SendMessageResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_a2a_service.SendMessageResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.send_message( + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_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].tenant + mock_val = "tenant_value" + assert arg == mock_val + arg = args[0].message + mock_val = data_a2a_service.A2AMessage(message_id="message_id_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_send_message_flattened_error_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.send_message( + data_a2a_service.SendMessageRequest(), + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_id_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + data_a2a_service.SendMessageRequest(), + {}, + ], +) +def test_send_streaming_message(request_type, transport: str = "grpc"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iter([data_a2a_service.StreamResponse()]) + response = client.send_streaming_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = data_a2a_service.SendMessageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, data_a2a_service.StreamResponse) + + +def test_send_streaming_message_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = data_a2a_service.SendMessageRequest( + tenant="tenant_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.send_streaming_message(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.SendMessageRequest( + tenant="tenant_value", + ) + assert args[0] == request_msg + + +def test_send_streaming_message_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.send_streaming_message + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.send_streaming_message] = ( + mock_rpc + ) + request = {} + client.send_streaming_message(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.send_streaming_message(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_send_streaming_message_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.send_streaming_message + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.send_streaming_message + ] = mock_rpc + + request = {} + await client.send_streaming_message(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.send_streaming_message(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + data_a2a_service.SendMessageRequest(), + {}, + ], +) +async def test_send_streaming_message_async( + request_type, transport: str = "grpc_asyncio" +): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock( + side_effect=[data_a2a_service.StreamResponse()] + ) + response = await client.send_streaming_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = data_a2a_service.SendMessageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, data_a2a_service.StreamResponse) + + +def test_send_streaming_message_field_headers(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_a2a_service.SendMessageRequest() + + request.tenant = "tenant_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + call.return_value = iter([data_a2a_service.StreamResponse()]) + client.send_streaming_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "tenant=tenant_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_send_streaming_message_field_headers_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_a2a_service.SendMessageRequest() + + request.tenant = "tenant_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock( + side_effect=[data_a2a_service.StreamResponse()] + ) + await client.send_streaming_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "tenant=tenant_value", + ) in kw["metadata"] + + +def test_send_streaming_message_flattened(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iter([data_a2a_service.StreamResponse()]) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.send_streaming_message( + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_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].tenant + mock_val = "tenant_value" + assert arg == mock_val + arg = args[0].message + mock_val = data_a2a_service.A2AMessage(message_id="message_id_value") + assert arg == mock_val + + +def test_send_streaming_message_flattened_error(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.send_streaming_message( + data_a2a_service.SendMessageRequest(), + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_id_value"), + ) + + +@pytest.mark.asyncio +async def test_send_streaming_message_flattened_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iter([data_a2a_service.StreamResponse()]) + + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.send_streaming_message( + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_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].tenant + mock_val = "tenant_value" + assert arg == mock_val + arg = args[0].message + mock_val = data_a2a_service.A2AMessage(message_id="message_id_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_send_streaming_message_flattened_error_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.send_streaming_message( + data_a2a_service.SendMessageRequest(), + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_id_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + data_a2a_service.GetAgentCardRequest(), + {}, + ], +) +def test_get_agent_card(request_type, transport: str = "grpc"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent_card), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = data_a2a_service.AgentCard( + protocol_version="protocol_version_value", + name="name_value", + description="description_value", + url="url_value", + preferred_transport="preferred_transport_value", + version="version_value", + documentation_url="documentation_url_value", + default_input_modes=["default_input_modes_value"], + default_output_modes=["default_output_modes_value"], + supports_authenticated_extended_card=True, + icon_url="icon_url_value", + ) + response = client.get_agent_card(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = data_a2a_service.GetAgentCardRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, data_a2a_service.AgentCard) + assert response.protocol_version == "protocol_version_value" + assert response.name == "name_value" + assert response.description == "description_value" + assert response.url == "url_value" + assert response.preferred_transport == "preferred_transport_value" + assert response.version == "version_value" + assert response.documentation_url == "documentation_url_value" + assert response.default_input_modes == ["default_input_modes_value"] + assert response.default_output_modes == ["default_output_modes_value"] + assert response.supports_authenticated_extended_card is True + assert response.icon_url == "icon_url_value" + + +def test_get_agent_card_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = data_a2a_service.GetAgentCardRequest( + tenant="tenant_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_agent_card), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_agent_card(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.GetAgentCardRequest( + tenant="tenant_value", + ) + assert args[0] == request_msg + + +def test_get_agent_card_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_agent_card in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_agent_card] = mock_rpc + request = {} + client.get_agent_card(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_agent_card(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_agent_card_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_agent_card + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_agent_card + ] = mock_rpc + + request = {} + await client.get_agent_card(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_agent_card(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + data_a2a_service.GetAgentCardRequest(), + {}, + ], +) +async def test_get_agent_card_async(request_type, transport: str = "grpc_asyncio"): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_agent_card), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_a2a_service.AgentCard( + protocol_version="protocol_version_value", + name="name_value", + description="description_value", + url="url_value", + preferred_transport="preferred_transport_value", + version="version_value", + documentation_url="documentation_url_value", + default_input_modes=["default_input_modes_value"], + default_output_modes=["default_output_modes_value"], + supports_authenticated_extended_card=True, + icon_url="icon_url_value", + ) + ) + response = await client.get_agent_card(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = data_a2a_service.GetAgentCardRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, data_a2a_service.AgentCard) + assert response.protocol_version == "protocol_version_value" + assert response.name == "name_value" + assert response.description == "description_value" + assert response.url == "url_value" + assert response.preferred_transport == "preferred_transport_value" + assert response.version == "version_value" + assert response.documentation_url == "documentation_url_value" + assert response.default_input_modes == ["default_input_modes_value"] + assert response.default_output_modes == ["default_output_modes_value"] + assert response.supports_authenticated_extended_card is True + assert response.icon_url == "icon_url_value" + + +def test_get_agent_card_field_headers(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_a2a_service.GetAgentCardRequest() + + request.tenant = "tenant_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_agent_card), "__call__") as call: + call.return_value = data_a2a_service.AgentCard() + client.get_agent_card(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "tenant=tenant_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_agent_card_field_headers_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_a2a_service.GetAgentCardRequest() + + request.tenant = "tenant_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_agent_card), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_a2a_service.AgentCard() + ) + await client.get_agent_card(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "tenant=tenant_value", + ) in kw["metadata"] + + +def test_get_agent_card_flattened(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_agent_card), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = data_a2a_service.AgentCard() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_agent_card( + tenant="tenant_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].tenant + mock_val = "tenant_value" + assert arg == mock_val + + +def test_get_agent_card_flattened_error(): + client = DataA2AServiceClient( + credentials=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_agent_card( + data_a2a_service.GetAgentCardRequest(), + tenant="tenant_value", + ) + + +@pytest.mark.asyncio +async def test_get_agent_card_flattened_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_agent_card), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = data_a2a_service.AgentCard() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_a2a_service.AgentCard() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_agent_card( + tenant="tenant_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].tenant + mock_val = "tenant_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_agent_card_flattened_error_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_agent_card( + data_a2a_service.GetAgentCardRequest(), + tenant="tenant_value", + ) + + +def test_send_message_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.send_message in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.send_message] = mock_rpc + + request = {} + client.send_message(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.send_message(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_send_message_rest_required_fields( + request_type=data_a2a_service.SendMessageRequest, +): + transport_class = transports.DataA2AServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseSendMessage, + "_BaseSendMessage__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # verify required fields with non-default values are left alone + + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = data_a2a_service.SendMessageResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_a2a_service.SendMessageResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.send_message(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_send_message_rest_flattened(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = data_a2a_service.SendMessageResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"tenant": "projects/sample1/locations/sample2/agents/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_id_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = data_a2a_service.SendMessageResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.send_message(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/a2a/{tenant=projects/*/locations/*/agents/*}/v1/message:send" + % client.transport._host, + args[1], + ) + + +def test_send_message_rest_flattened_error(transport: str = "rest"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.send_message( + data_a2a_service.SendMessageRequest(), + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_id_value"), + ) + + +def test_send_streaming_message_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.send_streaming_message + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.send_streaming_message] = ( + mock_rpc + ) + + request = {} + client.send_streaming_message(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.send_streaming_message(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_send_streaming_message_rest_required_fields( + request_type=data_a2a_service.SendMessageRequest, +): + transport_class = transports.DataA2AServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseSendStreamingMessage, + "_BaseSendStreamingMessage__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # verify required fields with non-default values are left alone + + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = data_a2a_service.StreamResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_a2a_service.StreamResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(json_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + with mock.patch.object(response_value, "iter_content") as iter_content: + iter_content.return_value = iter(json_return_value) + response = client.send_streaming_message(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_send_streaming_message_rest_flattened(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = data_a2a_service.StreamResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"tenant": "projects/sample1/locations/sample2/agents/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_id_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = data_a2a_service.StreamResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(json_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + with mock.patch.object(response_value, "iter_content") as iter_content: + iter_content.return_value = iter(json_return_value) + client.send_streaming_message(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/a2a/{tenant=projects/*/locations/*/agents/*}/v1/message:stream" + % client.transport._host, + args[1], + ) + + +def test_send_streaming_message_rest_flattened_error(transport: str = "rest"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.send_streaming_message( + data_a2a_service.SendMessageRequest(), + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_id_value"), + ) + + +def test_get_agent_card_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_agent_card in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_agent_card] = mock_rpc + + request = {} + client.get_agent_card(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_agent_card(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_agent_card_rest_flattened(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = data_a2a_service.AgentCard() + + # get arguments that satisfy an http rule for this method + sample_request = {"tenant": "projects/sample1/locations/sample2/agents/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + tenant="tenant_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = data_a2a_service.AgentCard.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_agent_card(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/a2a/{tenant=projects/*/locations/*/agents/*}/v1/card" + % client.transport._host, + args[1], + ) + + +def test_get_agent_card_rest_flattened_error(transport: str = "rest"): + client = DataA2AServiceClient( + credentials=ga_credentials.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_agent_card( + data_a2a_service.GetAgentCardRequest(), + tenant="tenant_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DataA2AServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DataA2AServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataA2AServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DataA2AServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DataA2AServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DataA2AServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DataA2AServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataA2AServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataA2AServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DataA2AServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataA2AServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DataA2AServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DataA2AServiceGrpcTransport, + transports.DataA2AServiceGrpcAsyncIOTransport, + transports.DataA2AServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = DataA2AServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_send_message_empty_call_grpc(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + call.return_value = data_a2a_service.SendMessageResponse() + client.send_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.SendMessageRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_send_streaming_message_empty_call_grpc(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + call.return_value = iter([data_a2a_service.StreamResponse()]) + client.send_streaming_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.SendMessageRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_agent_card_empty_call_grpc(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_agent_card), "__call__") as call: + call.return_value = data_a2a_service.AgentCard() + client.get_agent_card(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.GetAgentCardRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = DataA2AServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_send_message_empty_call_grpc_asyncio(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_a2a_service.SendMessageResponse() + ) + await client.send_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.SendMessageRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_send_streaming_message_empty_call_grpc_asyncio(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock( + side_effect=[data_a2a_service.StreamResponse()] + ) + await client.send_streaming_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.SendMessageRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_agent_card_empty_call_grpc_asyncio(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_agent_card), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_a2a_service.AgentCard( + protocol_version="protocol_version_value", + name="name_value", + description="description_value", + url="url_value", + preferred_transport="preferred_transport_value", + version="version_value", + documentation_url="documentation_url_value", + default_input_modes=["default_input_modes_value"], + default_output_modes=["default_output_modes_value"], + supports_authenticated_extended_card=True, + icon_url="icon_url_value", + ) + ) + await client.get_agent_card(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.GetAgentCardRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = DataA2AServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_send_message_rest_bad_request( + request_type=data_a2a_service.SendMessageRequest, +): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"tenant": "projects/sample1/locations/sample2/agents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.send_message(request) + + +@pytest.mark.parametrize( + "request_type", + [ + data_a2a_service.SendMessageRequest, + dict, + ], +) +def test_send_message_rest_call_success(request_type): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"tenant": "projects/sample1/locations/sample2/agents/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 = data_a2a_service.SendMessageResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_a2a_service.SendMessageResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.send_message(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, data_a2a_service.SendMessageResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_send_message_rest_interceptors(null_interceptor): + transport = transports.DataA2AServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DataA2AServiceRestInterceptor(), + ) + client = DataA2AServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DataA2AServiceRestInterceptor, "post_send_message" + ) as post, + mock.patch.object( + transports.DataA2AServiceRestInterceptor, "post_send_message_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.DataA2AServiceRestInterceptor, "pre_send_message" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = data_a2a_service.SendMessageRequest.pb( + data_a2a_service.SendMessageRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = data_a2a_service.SendMessageResponse.to_json( + data_a2a_service.SendMessageResponse() + ) + req.return_value.content = return_value + + request = data_a2a_service.SendMessageRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = data_a2a_service.SendMessageResponse() + post_with_metadata.return_value = ( + data_a2a_service.SendMessageResponse(), + metadata, + ) + + client.send_message( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_send_streaming_message_rest_bad_request( + request_type=data_a2a_service.SendMessageRequest, +): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"tenant": "projects/sample1/locations/sample2/agents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.send_streaming_message(request) + + +@pytest.mark.parametrize( + "request_type", + [ + data_a2a_service.SendMessageRequest, + dict, + ], +) +def test_send_streaming_message_rest_call_success(request_type): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"tenant": "projects/sample1/locations/sample2/agents/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 = data_a2a_service.StreamResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_a2a_service.StreamResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(json_return_value) + response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.send_streaming_message(request) + + assert isinstance(response, Iterable) + response = next(response) + + # Establish that the response is the type that we expect. + assert isinstance(response, data_a2a_service.StreamResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_send_streaming_message_rest_interceptors(null_interceptor): + transport = transports.DataA2AServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DataA2AServiceRestInterceptor(), + ) + client = DataA2AServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DataA2AServiceRestInterceptor, "post_send_streaming_message" + ) as post, + mock.patch.object( + transports.DataA2AServiceRestInterceptor, + "post_send_streaming_message_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DataA2AServiceRestInterceptor, "pre_send_streaming_message" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = data_a2a_service.SendMessageRequest.pb( + data_a2a_service.SendMessageRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = data_a2a_service.StreamResponse.to_json( + data_a2a_service.StreamResponse() + ) + req.return_value.iter_content = mock.Mock(return_value=iter(return_value)) + + request = data_a2a_service.SendMessageRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = data_a2a_service.StreamResponse() + post_with_metadata.return_value = data_a2a_service.StreamResponse(), metadata + + client.send_streaming_message( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_agent_card_rest_bad_request( + request_type=data_a2a_service.GetAgentCardRequest, +): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"tenant": "projects/sample1/locations/sample2/agents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_agent_card(request) + + +@pytest.mark.parametrize( + "request_type", + [ + data_a2a_service.GetAgentCardRequest, + dict, + ], +) +def test_get_agent_card_rest_call_success(request_type): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"tenant": "projects/sample1/locations/sample2/agents/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 = data_a2a_service.AgentCard( + protocol_version="protocol_version_value", + name="name_value", + description="description_value", + url="url_value", + preferred_transport="preferred_transport_value", + version="version_value", + documentation_url="documentation_url_value", + default_input_modes=["default_input_modes_value"], + default_output_modes=["default_output_modes_value"], + supports_authenticated_extended_card=True, + icon_url="icon_url_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_a2a_service.AgentCard.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_agent_card(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, data_a2a_service.AgentCard) + assert response.protocol_version == "protocol_version_value" + assert response.name == "name_value" + assert response.description == "description_value" + assert response.url == "url_value" + assert response.preferred_transport == "preferred_transport_value" + assert response.version == "version_value" + assert response.documentation_url == "documentation_url_value" + assert response.default_input_modes == ["default_input_modes_value"] + assert response.default_output_modes == ["default_output_modes_value"] + assert response.supports_authenticated_extended_card is True + assert response.icon_url == "icon_url_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_agent_card_rest_interceptors(null_interceptor): + transport = transports.DataA2AServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DataA2AServiceRestInterceptor(), + ) + client = DataA2AServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DataA2AServiceRestInterceptor, "post_get_agent_card" + ) as post, + mock.patch.object( + transports.DataA2AServiceRestInterceptor, + "post_get_agent_card_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DataA2AServiceRestInterceptor, "pre_get_agent_card" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = data_a2a_service.GetAgentCardRequest.pb( + data_a2a_service.GetAgentCardRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = data_a2a_service.AgentCard.to_json(data_a2a_service.AgentCard()) + req.return_value.content = return_value + + request = data_a2a_service.GetAgentCardRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = data_a2a_service.AgentCard() + post_with_metadata.return_value = data_a2a_service.AgentCard(), metadata + + client.get_agent_card( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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( + request_type=operations_pb2.DeleteOperationRequest, +): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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( + request_type=operations_pb2.GetOperationRequest, +): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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( + request_type=operations_pb2.ListOperationsRequest, +): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_send_message_empty_call_rest(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + client.send_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.SendMessageRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_send_streaming_message_empty_call_rest(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + client.send_streaming_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.SendMessageRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_agent_card_empty_call_rest(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_agent_card), "__call__") as call: + client.get_agent_card(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.GetAgentCardRequest() + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DataA2AServiceGrpcTransport, + ) + + +def test_data_a2a_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DataA2AServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_data_a2a_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.geminidataanalytics_v1alpha.services.data_a2a_service.transports.DataA2AServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.DataA2AServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "send_message", + "send_streaming_message", + "get_agent_card", + "get_location", + "list_locations", + "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() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_data_a2a_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.cloud.geminidataanalytics_v1alpha.services.data_a2a_service.transports.DataA2AServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataA2AServiceTransport( + 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_data_a2a_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.cloud.geminidataanalytics_v1alpha.services.data_a2a_service.transports.DataA2AServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataA2AServiceTransport() + adc.assert_called_once() + + +def test_data_a2a_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DataA2AServiceClient() + 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.DataA2AServiceGrpcTransport, + transports.DataA2AServiceGrpcAsyncIOTransport, + ], +) +def test_data_a2a_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DataA2AServiceGrpcTransport, + transports.DataA2AServiceGrpcAsyncIOTransport, + transports.DataA2AServiceRestTransport, + ], +) +def test_data_a2a_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DataA2AServiceGrpcTransport, grpc_helpers), + (transports.DataA2AServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_data_a2a_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "geminidataanalytics.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="geminidataanalytics.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DataA2AServiceGrpcTransport, + transports.DataA2AServiceGrpcAsyncIOTransport, + ], +) +def test_data_a2a_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_data_a2a_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.DataA2AServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_data_a2a_service_host_no_port(transport_name): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="geminidataanalytics.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "geminidataanalytics.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://geminidataanalytics.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_data_a2a_service_host_with_port(transport_name): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="geminidataanalytics.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "geminidataanalytics.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://geminidataanalytics.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_data_a2a_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DataA2AServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DataA2AServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.send_message._session + session2 = client2.transport.send_message._session + assert session1 != session2 + session1 = client1.transport.send_streaming_message._session + session2 = client2.transport.send_streaming_message._session + assert session1 != session2 + session1 = client1.transport.get_agent_card._session + session2 = client2.transport.get_agent_card._session + assert session1 != session2 + + +def test_data_a2a_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataA2AServiceGrpcTransport( + 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_data_a2a_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataA2AServiceGrpcAsyncIOTransport( + 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.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [ + transports.DataA2AServiceGrpcTransport, + transports.DataA2AServiceGrpcAsyncIOTransport, + ], +) +def test_data_a2a_service_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.DataA2AServiceGrpcTransport, + transports.DataA2AServiceGrpcAsyncIOTransport, + ], +) +def test_data_a2a_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = DataA2AServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = DataA2AServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DataA2AServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = DataA2AServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = DataA2AServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DataA2AServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = DataA2AServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = DataA2AServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DataA2AServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = DataA2AServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = DataA2AServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DataA2AServiceClient.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 = DataA2AServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = DataA2AServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DataA2AServiceClient.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.DataA2AServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.DataA2AServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = DataA2AServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.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 = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.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 = DataA2AServiceClient( + 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 = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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_delete_operation_flattened(): + client = DataA2AServiceClient( + 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 + + client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +@pytest.mark.asyncio +async def test_delete_operation_flattened_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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) + await client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +def test_cancel_operation(transport: str = "grpc"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_asyncio"): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.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 = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.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 = DataA2AServiceClient( + 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 = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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_cancel_operation_flattened(): + client = DataA2AServiceClient( + 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 + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +def test_get_operation(transport: str = "grpc"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = DataA2AServiceClient( + 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 = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation_flattened(): + client = DataA2AServiceClient( + 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() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +def test_list_operations(transport: str = "grpc"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.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 = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.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 = DataA2AServiceClient( + 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 = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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_list_operations_flattened(): + client = DataA2AServiceClient( + 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() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +def test_list_locations(transport: str = "grpc"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_locations_from_dict(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations_flattened(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +@pytest.mark.asyncio +async def test_list_locations_flattened_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +def test_get_location(transport: str = "grpc"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_get_location_field_headers(): + client = DataA2AServiceClient(credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = DataA2AServiceAsyncClient(credentials=async_anonymous_credentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +def test_get_location_from_dict(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location_flattened(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +@pytest.mark.asyncio +async def test_get_location_flattened_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +def test_transport_close_grpc(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = DataA2AServiceClient( + 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", + [ + (DataA2AServiceClient, transports.DataA2AServiceGrpcTransport), + (DataA2AServiceAsyncClient, transports.DataA2AServiceGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_agent_service.py b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_agent_service.py index d0c7322a8340..221aa7bd2fc5 100644 --- a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_agent_service.py +++ b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_agent_service.py @@ -2223,6 +2223,8 @@ def test_get_data_agent(request_type, transport: str = "grpc"): name="name_value", display_name="display_name_value", description="description_value", + kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) response = client.get_data_agent(request) @@ -2237,6 +2239,8 @@ def test_get_data_agent(request_type, transport: str = "grpc"): assert response.name == "name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" + assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True def test_get_data_agent_non_empty_request_with_auto_populated_field(): @@ -2371,6 +2375,8 @@ async def test_get_data_agent_async(request_type, transport: str = "grpc_asyncio name="name_value", display_name="display_name_value", description="description_value", + kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) ) response = await client.get_data_agent(request) @@ -2386,6 +2392,8 @@ async def test_get_data_agent_async(request_type, transport: str = "grpc_asyncio assert response.name == "name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" + assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True def test_get_data_agent_field_headers(): @@ -2959,6 +2967,8 @@ def test_create_data_agent_sync(request_type, transport: str = "grpc"): name="name_value", display_name="display_name_value", description="description_value", + kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) response = client.create_data_agent_sync(request) @@ -2973,6 +2983,8 @@ def test_create_data_agent_sync(request_type, transport: str = "grpc"): assert response.name == "name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" + assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True def test_create_data_agent_sync_non_empty_request_with_auto_populated_field(): @@ -3120,6 +3132,8 @@ async def test_create_data_agent_sync_async( name="name_value", display_name="display_name_value", description="description_value", + kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) ) response = await client.create_data_agent_sync(request) @@ -3135,6 +3149,8 @@ async def test_create_data_agent_sync_async( assert response.name == "name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" + assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True def test_create_data_agent_sync_field_headers(): @@ -3756,6 +3772,8 @@ def test_update_data_agent_sync(request_type, transport: str = "grpc"): name="name_value", display_name="display_name_value", description="description_value", + kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) response = client.update_data_agent_sync(request) @@ -3770,6 +3788,8 @@ def test_update_data_agent_sync(request_type, transport: str = "grpc"): assert response.name == "name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" + assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True def test_update_data_agent_sync_non_empty_request_with_auto_populated_field(): @@ -3911,6 +3931,8 @@ async def test_update_data_agent_sync_async( name="name_value", display_name="display_name_value", description="description_value", + kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) ) response = await client.update_data_agent_sync(request) @@ -3926,6 +3948,8 @@ async def test_update_data_agent_sync_async( assert response.name == "name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" + assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True def test_update_data_agent_sync_field_headers(): @@ -5485,6 +5509,758 @@ async def test_set_iam_policy_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + data_agent_service.SetAgentOpsObservabilityRequest(), + {}, + ], +) +def test_set_agent_ops_observability(request_type, transport: str = "grpc"): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.set_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = data_agent_service.SetAgentOpsObservabilityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_set_agent_ops_observability_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = data_agent_service.SetAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.set_agent_ops_observability(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.SetAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + assert args[0] == request_msg + + +def test_set_agent_ops_observability_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.set_agent_ops_observability + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.set_agent_ops_observability + ] = mock_rpc + request = {} + client.set_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.set_agent_ops_observability(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_set_agent_ops_observability_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.set_agent_ops_observability + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.set_agent_ops_observability + ] = mock_rpc + + request = {} + await client.set_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.set_agent_ops_observability(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + data_agent_service.SetAgentOpsObservabilityRequest(), + {}, + ], +) +async def test_set_agent_ops_observability_async( + request_type, transport: str = "grpc_asyncio" +): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__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.set_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = data_agent_service.SetAgentOpsObservabilityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_set_agent_ops_observability_field_headers(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_agent_service.SetAgentOpsObservabilityRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.set_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_set_agent_ops_observability_field_headers_async(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_agent_service.SetAgentOpsObservabilityRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.set_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_set_agent_ops_observability_flattened(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__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.set_agent_ops_observability( + parent="parent_value", + telemetry_enabled=True, + data_source_type="data_source_type_value", + ) + + # Establish that the 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].telemetry_enabled + mock_val = True + assert arg == mock_val + arg = args[0].data_source_type + mock_val = "data_source_type_value" + assert arg == mock_val + + +def test_set_agent_ops_observability_flattened_error(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_agent_ops_observability( + data_agent_service.SetAgentOpsObservabilityRequest(), + parent="parent_value", + telemetry_enabled=True, + data_source_type="data_source_type_value", + ) + + +@pytest.mark.asyncio +async def test_set_agent_ops_observability_flattened_async(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__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.set_agent_ops_observability( + parent="parent_value", + telemetry_enabled=True, + data_source_type="data_source_type_value", + ) + + # Establish that 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].telemetry_enabled + mock_val = True + assert arg == mock_val + arg = args[0].data_source_type + mock_val = "data_source_type_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_set_agent_ops_observability_flattened_error_async(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_agent_ops_observability( + data_agent_service.SetAgentOpsObservabilityRequest(), + parent="parent_value", + telemetry_enabled=True, + data_source_type="data_source_type_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + data_agent_service.RetrieveAgentOpsObservabilityRequest(), + {}, + ], +) +def test_retrieve_agent_ops_observability(request_type, transport: str = "grpc"): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse( + telemetry_enabled=True, + bigquery_enabled=True, + cloud_trace_enabled=True, + cloud_monitoring_enabled=True, + cloud_logging_enabled=True, + bqaa_enabled=True, + ) + response = client.retrieve_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = data_agent_service.RetrieveAgentOpsObservabilityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, data_agent_service.RetrieveAgentOpsObservabilityResponse + ) + assert response.telemetry_enabled is True + assert response.bigquery_enabled is True + assert response.cloud_trace_enabled is True + assert response.cloud_monitoring_enabled is True + assert response.cloud_logging_enabled is True + assert response.bqaa_enabled is True + + +def test_retrieve_agent_ops_observability_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = data_agent_service.RetrieveAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.retrieve_agent_ops_observability(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.RetrieveAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + assert args[0] == request_msg + + +def test_retrieve_agent_ops_observability_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.retrieve_agent_ops_observability + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.retrieve_agent_ops_observability + ] = mock_rpc + request = {} + client.retrieve_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.retrieve_agent_ops_observability(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_retrieve_agent_ops_observability_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.retrieve_agent_ops_observability + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.retrieve_agent_ops_observability + ] = mock_rpc + + request = {} + await client.retrieve_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.retrieve_agent_ops_observability(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + data_agent_service.RetrieveAgentOpsObservabilityRequest(), + {}, + ], +) +async def test_retrieve_agent_ops_observability_async( + request_type, transport: str = "grpc_asyncio" +): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_agent_service.RetrieveAgentOpsObservabilityResponse( + telemetry_enabled=True, + bigquery_enabled=True, + cloud_trace_enabled=True, + cloud_monitoring_enabled=True, + cloud_logging_enabled=True, + bqaa_enabled=True, + ) + ) + response = await client.retrieve_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = data_agent_service.RetrieveAgentOpsObservabilityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, data_agent_service.RetrieveAgentOpsObservabilityResponse + ) + assert response.telemetry_enabled is True + assert response.bigquery_enabled is True + assert response.cloud_trace_enabled is True + assert response.cloud_monitoring_enabled is True + assert response.cloud_logging_enabled is True + assert response.bqaa_enabled is True + + +def test_retrieve_agent_ops_observability_field_headers(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_agent_service.RetrieveAgentOpsObservabilityRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + call.return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() + client.retrieve_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_retrieve_agent_ops_observability_field_headers_async(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_agent_service.RetrieveAgentOpsObservabilityRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_agent_service.RetrieveAgentOpsObservabilityResponse() + ) + await client.retrieve_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_retrieve_agent_ops_observability_flattened(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.retrieve_agent_ops_observability( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Establish that the 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].data_source_type + mock_val = "data_source_type_value" + assert arg == mock_val + + +def test_retrieve_agent_ops_observability_flattened_error(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.retrieve_agent_ops_observability( + data_agent_service.RetrieveAgentOpsObservabilityRequest(), + parent="parent_value", + data_source_type="data_source_type_value", + ) + + +@pytest.mark.asyncio +async def test_retrieve_agent_ops_observability_flattened_async(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_agent_service.RetrieveAgentOpsObservabilityResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.retrieve_agent_ops_observability( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Establish that 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].data_source_type + mock_val = "data_source_type_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_retrieve_agent_ops_observability_flattened_error_async(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.retrieve_agent_ops_observability( + data_agent_service.RetrieveAgentOpsObservabilityRequest(), + parent="parent_value", + data_source_type="data_source_type_value", + ) + + def test_list_data_agents_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5499,32 +6275,284 @@ def test_list_data_agents_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_data_agents in client._transport._wrapped_methods + assert client._transport.list_data_agents in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_data_agents] = ( + mock_rpc + ) + + request = {} + client.list_data_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_agents(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_data_agents_rest_required_fields( + request_type=data_agent_service.ListDataAgentsRequest, +): + transport_class = transports.DataAgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListDataAgents, + "_BaseListDataAgents__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "creatorFilter", + "filter", + "orderBy", + "pageSize", + "pageToken", + "showDeleted", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = data_agent_service.ListDataAgentsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_agent_service.ListDataAgentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_data_agents(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_data_agents_rest_flattened(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = data_agent_service.ListDataAgentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = data_agent_service.ListDataAgentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_data_agents(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=projects/*/locations/*}/dataAgents" + % client.transport._host, + args[1], + ) + + +def test_list_data_agents_rest_flattened_error(transport: str = "rest"): + client = DataAgentServiceClient( + credentials=ga_credentials.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_data_agents( + data_agent_service.ListDataAgentsRequest(), + parent="parent_value", + ) + + +def test_list_data_agents_rest_pager(transport: str = "rest"): + client = DataAgentServiceClient( + 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 = ( + data_agent_service.ListDataAgentsResponse( + data_agents=[ + data_agent.DataAgent(), + data_agent.DataAgent(), + data_agent.DataAgent(), + ], + next_page_token="abc", + ), + data_agent_service.ListDataAgentsResponse( + data_agents=[], + next_page_token="def", + ), + data_agent_service.ListDataAgentsResponse( + data_agents=[ + data_agent.DataAgent(), + ], + next_page_token="ghi", + ), + data_agent_service.ListDataAgentsResponse( + data_agents=[ + data_agent.DataAgent(), + data_agent.DataAgent(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + data_agent_service.ListDataAgentsResponse.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_data_agents(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, data_agent.DataAgent) for i in results) + + pages = list(client.list_data_agents(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_accessible_data_agents_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_accessible_data_agents + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_data_agents] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_accessible_data_agents + ] = mock_rpc request = {} - client.list_data_agents(request) + client.list_accessible_data_agents(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_data_agents(request) + client.list_accessible_data_agents(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_data_agents_rest_required_fields( - request_type=data_agent_service.ListDataAgentsRequest, +def test_list_accessible_data_agents_rest_required_fields( + request_type=data_agent_service.ListAccessibleDataAgentsRequest, ): transport_class = transports.DataAgentServiceRestTransport @@ -5539,8 +6567,8 @@ def test_list_data_agents_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListDataAgents, - "_BaseListDataAgents__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListAccessibleDataAgents, + "_BaseListAccessibleDataAgents__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -5555,6 +6583,7 @@ def test_list_data_agents_rest_required_fields( # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( + "creatorFilter", "filter", "orderBy", "pageSize", @@ -5564,8 +6593,248 @@ def test_list_data_agents_rest_required_fields( ) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = data_agent_service.ListAccessibleDataAgentsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_agent_service.ListAccessibleDataAgentsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_accessible_data_agents(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_accessible_data_agents_rest_flattened(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = data_agent_service.ListAccessibleDataAgentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = data_agent_service.ListAccessibleDataAgentsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_accessible_data_agents(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=projects/*/locations/*}/dataAgents:listAccessible" + % client.transport._host, + args[1], + ) + + +def test_list_accessible_data_agents_rest_flattened_error(transport: str = "rest"): + client = DataAgentServiceClient( + credentials=ga_credentials.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_accessible_data_agents( + data_agent_service.ListAccessibleDataAgentsRequest(), + parent="parent_value", + ) + + +def test_list_accessible_data_agents_rest_pager(transport: str = "rest"): + client = DataAgentServiceClient( + 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 = ( + data_agent_service.ListAccessibleDataAgentsResponse( + data_agents=[ + data_agent.DataAgent(), + data_agent.DataAgent(), + data_agent.DataAgent(), + ], + next_page_token="abc", + ), + data_agent_service.ListAccessibleDataAgentsResponse( + data_agents=[], + next_page_token="def", + ), + data_agent_service.ListAccessibleDataAgentsResponse( + data_agents=[ + data_agent.DataAgent(), + ], + next_page_token="ghi", + ), + data_agent_service.ListAccessibleDataAgentsResponse( + data_agents=[ + data_agent.DataAgent(), + data_agent.DataAgent(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + data_agent_service.ListAccessibleDataAgentsResponse.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_accessible_data_agents(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, data_agent.DataAgent) for i in results) + + pages = list(client.list_accessible_data_agents(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_data_agent_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_agent in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_data_agent] = mock_rpc + + request = {} + client.get_data_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_agent(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_data_agent_rest_required_fields( + request_type=data_agent_service.GetDataAgentRequest, +): + transport_class = transports.DataAgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetDataAgent, + "_BaseGetDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5574,7 +6843,7 @@ def test_list_data_agents_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = data_agent_service.ListDataAgentsResponse() + return_value = data_agent.DataAgent() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -5595,21 +6864,21 @@ def test_list_data_agents_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = data_agent_service.ListDataAgentsResponse.pb(return_value) + return_value = data_agent.DataAgent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_data_agents(request) + response = client.get_data_agent(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_data_agents_rest_flattened(): +def test_get_data_agent_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5618,14 +6887,16 @@ def test_list_data_agents_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = data_agent_service.ListDataAgentsResponse() + return_value = data_agent.DataAgent() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "name": "projects/sample1/locations/sample2/dataAgents/sample3" + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) @@ -5633,26 +6904,26 @@ def test_list_data_agents_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = data_agent_service.ListDataAgentsResponse.pb(return_value) + return_value = data_agent.DataAgent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_data_agents(**mock_args) + client.get_data_agent(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=projects/*/locations/*}/dataAgents" + "%s/v1alpha/{name=projects/*/locations/*/dataAgents/*}" % client.transport._host, args[1], ) -def test_list_data_agents_rest_flattened_error(transport: str = "rest"): +def test_get_data_agent_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5661,79 +6932,13 @@ def test_list_data_agents_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_data_agents( - data_agent_service.ListDataAgentsRequest(), - parent="parent_value", - ) - - -def test_list_data_agents_rest_pager(transport: str = "rest"): - client = DataAgentServiceClient( - 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 = ( - data_agent_service.ListDataAgentsResponse( - data_agents=[ - data_agent.DataAgent(), - data_agent.DataAgent(), - data_agent.DataAgent(), - ], - next_page_token="abc", - ), - data_agent_service.ListDataAgentsResponse( - data_agents=[], - next_page_token="def", - ), - data_agent_service.ListDataAgentsResponse( - data_agents=[ - data_agent.DataAgent(), - ], - next_page_token="ghi", - ), - data_agent_service.ListDataAgentsResponse( - data_agents=[ - data_agent.DataAgent(), - data_agent.DataAgent(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - data_agent_service.ListDataAgentsResponse.to_json(x) for x in response + client.get_data_agent( + data_agent_service.GetDataAgentRequest(), + name="name_value", ) - 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_data_agents(request=sample_request) - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, data_agent.DataAgent) for i in results) - - pages = list(client.list_data_agents(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - -def test_list_accessible_data_agents_rest_use_cached_wrapped_rpc(): +def test_create_data_agent_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5747,35 +6952,36 @@ def test_list_accessible_data_agents_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_accessible_data_agents - in client._transport._wrapped_methods - ) + assert client._transport.create_data_agent in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.list_accessible_data_agents - ] = mock_rpc + client._transport._wrapped_methods[client._transport.create_data_agent] = ( + mock_rpc + ) request = {} - client.list_accessible_data_agents(request) + client.create_data_agent(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_accessible_data_agents(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_data_agent(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_accessible_data_agents_rest_required_fields( - request_type=data_agent_service.ListAccessibleDataAgentsRequest, +def test_create_data_agent_rest_required_fields( + request_type=data_agent_service.CreateDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport @@ -5790,8 +6996,8 @@ def test_list_accessible_data_agents_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListAccessibleDataAgents, - "_BaseListAccessibleDataAgents__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseCreateDataAgent, + "_BaseCreateDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -5806,12 +7012,8 @@ def test_list_accessible_data_agents_rest_required_fields( # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "creatorFilter", - "filter", - "orderBy", - "pageSize", - "pageToken", - "showDeleted", + "dataAgentId", + "requestId", ) ) @@ -5826,7 +7028,7 @@ def test_list_accessible_data_agents_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = data_agent_service.ListAccessibleDataAgentsResponse() + 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 @@ -5838,32 +7040,28 @@ def test_list_accessible_data_agents_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = data_agent_service.ListAccessibleDataAgentsResponse.pb( - return_value - ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_accessible_data_agents(request) + response = client.create_data_agent(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_accessible_data_agents_rest_flattened(): +def test_create_data_agent_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5872,7 +7070,7 @@ def test_list_accessible_data_agents_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = data_agent_service.ListAccessibleDataAgentsResponse() + 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"} @@ -5880,117 +7078,62 @@ def test_list_accessible_data_agents_rest_flattened(): # get truthy value for each flattened field mock_args = dict( parent="parent_value", + data_agent=gcg_data_agent.DataAgent( + data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( + staging_context=context.Context( + system_instruction="system_instruction_value" + ) + ) + ), + data_agent_id="data_agent_id_value", ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = data_agent_service.ListAccessibleDataAgentsResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_accessible_data_agents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{parent=projects/*/locations/*}/dataAgents:listAccessible" - % client.transport._host, - args[1], - ) - - -def test_list_accessible_data_agents_rest_flattened_error(transport: str = "rest"): - client = DataAgentServiceClient( - credentials=ga_credentials.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_accessible_data_agents( - data_agent_service.ListAccessibleDataAgentsRequest(), - parent="parent_value", - ) - - -def test_list_accessible_data_agents_rest_pager(transport: str = "rest"): - client = DataAgentServiceClient( - 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 = ( - data_agent_service.ListAccessibleDataAgentsResponse( - data_agents=[ - data_agent.DataAgent(), - data_agent.DataAgent(), - data_agent.DataAgent(), - ], - next_page_token="abc", - ), - data_agent_service.ListAccessibleDataAgentsResponse( - data_agents=[], - next_page_token="def", - ), - data_agent_service.ListAccessibleDataAgentsResponse( - data_agents=[ - data_agent.DataAgent(), - ], - next_page_token="ghi", - ), - data_agent_service.ListAccessibleDataAgentsResponse( - data_agents=[ - data_agent.DataAgent(), - data_agent.DataAgent(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - data_agent_service.ListAccessibleDataAgentsResponse.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 + mock_args.update(sample_request) - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - pager = client.list_accessible_data_agents(request=sample_request) + client.create_data_agent(**mock_args) - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=projects/*/locations/*}/dataAgents" + % client.transport._host, + args[1], + ) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, data_agent.DataAgent) for i in results) - pages = list(client.list_accessible_data_agents(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token +def test_create_data_agent_rest_flattened_error(transport: str = "rest"): + client = DataAgentServiceClient( + credentials=ga_credentials.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_data_agent( + data_agent_service.CreateDataAgentRequest(), + parent="parent_value", + data_agent=gcg_data_agent.DataAgent( + data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( + staging_context=context.Context( + system_instruction="system_instruction_value" + ) + ) + ), + data_agent_id="data_agent_id_value", + ) -def test_get_data_agent_rest_use_cached_wrapped_rpc(): +def test_create_data_agent_sync_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6004,35 +7147,40 @@ def test_get_data_agent_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_data_agent in client._transport._wrapped_methods + assert ( + client._transport.create_data_agent_sync + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_data_agent] = mock_rpc + client._transport._wrapped_methods[client._transport.create_data_agent_sync] = ( + mock_rpc + ) request = {} - client.get_data_agent(request) + client.create_data_agent_sync(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_data_agent(request) + client.create_data_agent_sync(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_data_agent_rest_required_fields( - request_type=data_agent_service.GetDataAgentRequest, +def test_create_data_agent_sync_rest_required_fields( + request_type=data_agent_service.CreateDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6042,8 +7190,8 @@ def test_get_data_agent_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetDataAgent, - "_BaseGetDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseCreateDataAgentSync, + "_BaseCreateDataAgentSync__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6053,11 +7201,19 @@ def test_get_data_agent_rest_required_fields( # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "dataAgentId", + "requestId", + ) + ) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6066,7 +7222,7 @@ def test_get_data_agent_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = data_agent.DataAgent() + return_value = gcg_data_agent.DataAgent() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -6078,30 +7234,31 @@ def test_get_data_agent_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = data_agent.DataAgent.pb(return_value) + return_value = gcg_data_agent.DataAgent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_data_agent(request) + response = client.create_data_agent_sync(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_data_agent_rest_flattened(): +def test_create_data_agent_sync_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6110,16 +7267,22 @@ def test_get_data_agent_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = data_agent.DataAgent() + return_value = gcg_data_agent.DataAgent() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/dataAgents/sample3" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + data_agent=gcg_data_agent.DataAgent( + data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( + staging_context=context.Context( + system_instruction="system_instruction_value" + ) + ) + ), + data_agent_id="data_agent_id_value", ) mock_args.update(sample_request) @@ -6127,26 +7290,26 @@ def test_get_data_agent_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = data_agent.DataAgent.pb(return_value) + return_value = gcg_data_agent.DataAgent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_data_agent(**mock_args) + client.create_data_agent_sync(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=projects/*/locations/*/dataAgents/*}" + "%s/v1alpha/{parent=projects/*/locations/*}/dataAgents:createSync" % client.transport._host, args[1], ) -def test_get_data_agent_rest_flattened_error(transport: str = "rest"): +def test_create_data_agent_sync_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6155,13 +7318,21 @@ def test_get_data_agent_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_data_agent( - data_agent_service.GetDataAgentRequest(), - name="name_value", + client.create_data_agent_sync( + data_agent_service.CreateDataAgentRequest(), + parent="parent_value", + data_agent=gcg_data_agent.DataAgent( + data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( + staging_context=context.Context( + system_instruction="system_instruction_value" + ) + ) + ), + data_agent_id="data_agent_id_value", ) -def test_create_data_agent_rest_use_cached_wrapped_rpc(): +def test_update_data_agent_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6175,19 +7346,19 @@ def test_create_data_agent_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_data_agent in client._transport._wrapped_methods + assert client._transport.update_data_agent in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_data_agent] = ( + client._transport._wrapped_methods[client._transport.update_data_agent] = ( mock_rpc ) request = {} - client.create_data_agent(request) + client.update_data_agent(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6196,20 +7367,19 @@ def test_create_data_agent_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_data_agent(request) + client.update_data_agent(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_data_agent_rest_required_fields( - request_type=data_agent_service.CreateDataAgentRequest, +def test_update_data_agent_rest_required_fields( + request_type=data_agent_service.UpdateDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6219,8 +7389,8 @@ def test_create_data_agent_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseCreateDataAgent, - "_BaseCreateDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseUpdateDataAgent, + "_BaseUpdateDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6230,19 +7400,15 @@ def test_create_data_agent_rest_required_fields( # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "dataAgentId", "requestId", + "updateMask", ) ) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6263,7 +7429,7 @@ def test_create_data_agent_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -6277,14 +7443,14 @@ def test_create_data_agent_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_data_agent(request) + response = client.update_data_agent(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_data_agent_rest_flattened(): +def test_update_data_agent_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6296,11 +7462,14 @@ def test_create_data_agent_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "data_agent": { + "name": "projects/sample1/locations/sample2/dataAgents/sample3" + } + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", data_agent=gcg_data_agent.DataAgent( data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( staging_context=context.Context( @@ -6308,7 +7477,7 @@ def test_create_data_agent_rest_flattened(): ) ) ), - data_agent_id="data_agent_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -6320,20 +7489,20 @@ def test_create_data_agent_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_data_agent(**mock_args) + client.update_data_agent(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=projects/*/locations/*}/dataAgents" + "%s/v1alpha/{data_agent.name=projects/*/locations/*/dataAgents/*}" % client.transport._host, args[1], ) -def test_create_data_agent_rest_flattened_error(transport: str = "rest"): +def test_update_data_agent_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6342,9 +7511,8 @@ def test_create_data_agent_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_data_agent( - data_agent_service.CreateDataAgentRequest(), - parent="parent_value", + client.update_data_agent( + data_agent_service.UpdateDataAgentRequest(), data_agent=gcg_data_agent.DataAgent( data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( staging_context=context.Context( @@ -6352,11 +7520,11 @@ def test_create_data_agent_rest_flattened_error(transport: str = "rest"): ) ) ), - data_agent_id="data_agent_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_create_data_agent_sync_rest_use_cached_wrapped_rpc(): +def test_update_data_agent_sync_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6371,7 +7539,7 @@ def test_create_data_agent_sync_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_data_agent_sync + client._transport.update_data_agent_sync in client._transport._wrapped_methods ) @@ -6380,30 +7548,29 @@ def test_create_data_agent_sync_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_data_agent_sync] = ( + client._transport._wrapped_methods[client._transport.update_data_agent_sync] = ( mock_rpc ) request = {} - client.create_data_agent_sync(request) + client.update_data_agent_sync(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_data_agent_sync(request) + client.update_data_agent_sync(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_data_agent_sync_rest_required_fields( - request_type=data_agent_service.CreateDataAgentRequest, +def test_update_data_agent_sync_rest_required_fields( + request_type=data_agent_service.UpdateDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6413,8 +7580,8 @@ def test_create_data_agent_sync_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseCreateDataAgentSync, - "_BaseCreateDataAgentSync__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseUpdateDataAgentSync, + "_BaseUpdateDataAgentSync__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6424,19 +7591,15 @@ def test_create_data_agent_sync_rest_required_fields( # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "dataAgentId", "requestId", + "updateMask", ) ) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6457,7 +7620,7 @@ def test_create_data_agent_sync_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -6474,14 +7637,14 @@ def test_create_data_agent_sync_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_data_agent_sync(request) + response = client.update_data_agent_sync(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_data_agent_sync_rest_flattened(): +def test_update_data_agent_sync_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6493,11 +7656,14 @@ def test_create_data_agent_sync_rest_flattened(): return_value = gcg_data_agent.DataAgent() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "data_agent": { + "name": "projects/sample1/locations/sample2/dataAgents/sample3" + } + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", data_agent=gcg_data_agent.DataAgent( data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( staging_context=context.Context( @@ -6505,7 +7671,7 @@ def test_create_data_agent_sync_rest_flattened(): ) ) ), - data_agent_id="data_agent_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -6519,20 +7685,20 @@ def test_create_data_agent_sync_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_data_agent_sync(**mock_args) + client.update_data_agent_sync(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=projects/*/locations/*}/dataAgents:createSync" + "%s/v1alpha/{data_agent.name=projects/*/locations/*/dataAgents/*}:updateSync" % client.transport._host, args[1], ) -def test_create_data_agent_sync_rest_flattened_error(transport: str = "rest"): +def test_update_data_agent_sync_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6541,9 +7707,8 @@ def test_create_data_agent_sync_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_data_agent_sync( - data_agent_service.CreateDataAgentRequest(), - parent="parent_value", + client.update_data_agent_sync( + data_agent_service.UpdateDataAgentRequest(), data_agent=gcg_data_agent.DataAgent( data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( staging_context=context.Context( @@ -6551,11 +7716,11 @@ def test_create_data_agent_sync_rest_flattened_error(transport: str = "rest"): ) ) ), - data_agent_id="data_agent_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_update_data_agent_rest_use_cached_wrapped_rpc(): +def test_delete_data_agent_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6569,19 +7734,19 @@ def test_update_data_agent_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_data_agent in client._transport._wrapped_methods + assert client._transport.delete_data_agent in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_data_agent] = ( + client._transport._wrapped_methods[client._transport.delete_data_agent] = ( mock_rpc ) request = {} - client.update_data_agent(request) + client.delete_data_agent(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6590,19 +7755,20 @@ def test_update_data_agent_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_data_agent(request) + client.delete_data_agent(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_data_agent_rest_required_fields( - request_type=data_agent_service.UpdateDataAgentRequest, +def test_delete_data_agent_rest_required_fields( + request_type=data_agent_service.DeleteDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6612,8 +7778,8 @@ def test_update_data_agent_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseUpdateDataAgent, - "_BaseUpdateDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseDeleteDataAgent, + "_BaseDeleteDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6623,15 +7789,14 @@ def test_update_data_agent_rest_required_fields( # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "requestId", - "updateMask", - ) - ) + assert not set(unset_fields) - set(("requestId",)) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6652,10 +7817,9 @@ def test_update_data_agent_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -6666,14 +7830,14 @@ def test_update_data_agent_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_data_agent(request) + response = client.delete_data_agent(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_data_agent_rest_flattened(): +def test_delete_data_agent_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6686,21 +7850,12 @@ def test_update_data_agent_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "data_agent": { - "name": "projects/sample1/locations/sample2/dataAgents/sample3" - } + "name": "projects/sample1/locations/sample2/dataAgents/sample3" } # get truthy value for each flattened field mock_args = dict( - data_agent=gcg_data_agent.DataAgent( - data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( - staging_context=context.Context( - system_instruction="system_instruction_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -6712,20 +7867,20 @@ def test_update_data_agent_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_data_agent(**mock_args) + client.delete_data_agent(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{data_agent.name=projects/*/locations/*/dataAgents/*}" + "%s/v1alpha/{name=projects/*/locations/*/dataAgents/*}" % client.transport._host, args[1], ) -def test_update_data_agent_rest_flattened_error(transport: str = "rest"): +def test_delete_data_agent_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6734,20 +7889,13 @@ def test_update_data_agent_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_data_agent( - data_agent_service.UpdateDataAgentRequest(), - data_agent=gcg_data_agent.DataAgent( - data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( - staging_context=context.Context( - system_instruction="system_instruction_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_data_agent( + data_agent_service.DeleteDataAgentRequest(), + name="name_value", ) -def test_update_data_agent_sync_rest_use_cached_wrapped_rpc(): +def test_delete_data_agent_sync_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6762,7 +7910,7 @@ def test_update_data_agent_sync_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_data_agent_sync + client._transport.delete_data_agent_sync in client._transport._wrapped_methods ) @@ -6771,29 +7919,30 @@ def test_update_data_agent_sync_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_data_agent_sync] = ( + client._transport._wrapped_methods[client._transport.delete_data_agent_sync] = ( mock_rpc ) request = {} - client.update_data_agent_sync(request) + client.delete_data_agent_sync(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_data_agent_sync(request) + client.delete_data_agent_sync(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_data_agent_sync_rest_required_fields( - request_type=data_agent_service.UpdateDataAgentRequest, +def test_delete_data_agent_sync_rest_required_fields( + request_type=data_agent_service.DeleteDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6803,8 +7952,8 @@ def test_update_data_agent_sync_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseUpdateDataAgentSync, - "_BaseUpdateDataAgentSync__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseDeleteDataAgentSync, + "_BaseDeleteDataAgentSync__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6814,15 +7963,14 @@ def test_update_data_agent_sync_rest_required_fields( # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "requestId", - "updateMask", - ) - ) + assert not set(unset_fields) - set(("requestId",)) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6831,7 +7979,7 @@ def test_update_data_agent_sync_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gcg_data_agent.DataAgent() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -6843,31 +7991,27 @@ def test_update_data_agent_sync_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gcg_data_agent.DataAgent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_data_agent_sync(request) + response = client.delete_data_agent_sync(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_data_agent_sync_rest_flattened(): +def test_delete_data_agent_sync_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6876,52 +8020,41 @@ def test_update_data_agent_sync_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gcg_data_agent.DataAgent() + return_value = None # get arguments that satisfy an http rule for this method sample_request = { - "data_agent": { - "name": "projects/sample1/locations/sample2/dataAgents/sample3" - } + "name": "projects/sample1/locations/sample2/dataAgents/sample3" } # get truthy value for each flattened field mock_args = dict( - data_agent=gcg_data_agent.DataAgent( - data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( - staging_context=context.Context( - system_instruction="system_instruction_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcg_data_agent.DataAgent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_data_agent_sync(**mock_args) + client.delete_data_agent_sync(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{data_agent.name=projects/*/locations/*/dataAgents/*}:updateSync" + "%s/v1alpha/{name=projects/*/locations/*/dataAgents/*}:deleteSync" % client.transport._host, args[1], ) -def test_update_data_agent_sync_rest_flattened_error(transport: str = "rest"): +def test_delete_data_agent_sync_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6930,20 +8063,13 @@ def test_update_data_agent_sync_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_data_agent_sync( - data_agent_service.UpdateDataAgentRequest(), - data_agent=gcg_data_agent.DataAgent( - data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( - staging_context=context.Context( - system_instruction="system_instruction_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_data_agent_sync( + data_agent_service.DeleteDataAgentRequest(), + name="name_value", ) -def test_delete_data_agent_rest_use_cached_wrapped_rpc(): +def test_get_iam_policy_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6957,43 +8083,37 @@ def test_delete_data_agent_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_data_agent in client._transport._wrapped_methods + assert client._transport.get_iam_policy in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_data_agent] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_iam_policy] = mock_rpc request = {} - client.delete_data_agent(request) + client.get_iam_policy(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_data_agent(request) + client.get_iam_policy(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_data_agent_rest_required_fields( - request_type=data_agent_service.DeleteDataAgentRequest, +def test_get_iam_policy_rest_required_fields( + request_type=iam_policy_pb2.GetIamPolicyRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["resource"] = "" request = request_type(**request_init) - pb_request = request_type.pb(request) + pb_request = request jsonified_request = json.loads( json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) @@ -7001,8 +8121,8 @@ def test_delete_data_agent_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseDeleteDataAgent, - "_BaseDeleteDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetIamPolicy, + "_BaseGetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7012,14 +8132,11 @@ def test_delete_data_agent_rest_required_fields( # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("requestId",)) + jsonified_request["resource"] = "resource_value" # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7028,7 +8145,7 @@ def test_delete_data_agent_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = policy_pb2.Policy() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7037,30 +8154,32 @@ def test_delete_data_agent_rest_required_fields( with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. - pb_request = request_type.pb(request) + pb_request = request transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "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 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_data_agent(request) + response = client.get_iam_policy(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_data_agent_rest_flattened(): +def test_get_iam_policy_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7069,16 +8188,16 @@ def test_delete_data_agent_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = policy_pb2.Policy() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/dataAgents/sample3" + "resource": "projects/sample1/locations/sample2/dataAgents/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + resource="resource_value", ) mock_args.update(sample_request) @@ -7090,20 +8209,20 @@ def test_delete_data_agent_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_data_agent(**mock_args) + client.get_iam_policy(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=projects/*/locations/*/dataAgents/*}" + "%s/v1alpha/{resource=projects/*/locations/*/dataAgents/*}:getIamPolicy" % client.transport._host, args[1], ) -def test_delete_data_agent_rest_flattened_error(transport: str = "rest"): +def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7112,13 +8231,13 @@ def test_delete_data_agent_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_data_agent( - data_agent_service.DeleteDataAgentRequest(), - name="name_value", + client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource="resource_value", ) -def test_delete_data_agent_sync_rest_use_cached_wrapped_rpc(): +def test_set_iam_policy_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7132,42 +8251,37 @@ def test_delete_data_agent_sync_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_data_agent_sync - in client._transport._wrapped_methods - ) + assert client._transport.set_iam_policy in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_data_agent_sync] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.set_iam_policy] = mock_rpc request = {} - client.delete_data_agent_sync(request) + client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_data_agent_sync(request) + client.set_iam_policy(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_data_agent_sync_rest_required_fields( - request_type=data_agent_service.DeleteDataAgentRequest, +def test_set_iam_policy_rest_required_fields( + request_type=iam_policy_pb2.SetIamPolicyRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["resource"] = "" request = request_type(**request_init) - pb_request = request_type.pb(request) + pb_request = request jsonified_request = json.loads( json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) @@ -7175,8 +8289,8 @@ def test_delete_data_agent_sync_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseDeleteDataAgentSync, - "_BaseDeleteDataAgentSync__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseSetIamPolicy, + "_BaseSetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7186,14 +8300,11 @@ def test_delete_data_agent_sync_rest_required_fields( # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("requestId",)) + jsonified_request["resource"] = "resource_value" # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7202,7 +8313,7 @@ def test_delete_data_agent_sync_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = policy_pb2.Policy() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7211,30 +8322,32 @@ def test_delete_data_agent_sync_rest_required_fields( with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. - pb_request = request_type.pb(request) + pb_request = request transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "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_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_data_agent_sync(request) + response = client.set_iam_policy(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_data_agent_sync_rest_flattened(): +def test_set_iam_policy_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7243,41 +8356,41 @@ def test_delete_data_agent_sync_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = policy_pb2.Policy() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/dataAgents/sample3" + "resource": "projects/sample1/locations/sample2/dataAgents/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + resource="resource_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_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_data_agent_sync(**mock_args) + client.set_iam_policy(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=projects/*/locations/*/dataAgents/*}:deleteSync" + "%s/v1alpha/{resource=projects/*/locations/*/dataAgents/*}:setIamPolicy" % client.transport._host, args[1], ) -def test_delete_data_agent_sync_rest_flattened_error(transport: str = "rest"): +def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7286,13 +8399,13 @@ def test_delete_data_agent_sync_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_data_agent_sync( - data_agent_service.DeleteDataAgentRequest(), - name="name_value", + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource="resource_value", ) -def test_get_iam_policy_rest_use_cached_wrapped_rpc(): +def test_set_agent_ops_observability_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7306,37 +8419,47 @@ def test_get_iam_policy_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_iam_policy in client._transport._wrapped_methods + assert ( + client._transport.set_agent_ops_observability + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_iam_policy] = mock_rpc + client._transport._wrapped_methods[ + client._transport.set_agent_ops_observability + ] = mock_rpc request = {} - client.get_iam_policy(request) + client.set_agent_ops_observability(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_iam_policy(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.set_agent_ops_observability(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_iam_policy_rest_required_fields( - request_type=iam_policy_pb2.GetIamPolicyRequest, +def test_set_agent_ops_observability_rest_required_fields( + request_type=data_agent_service.SetAgentOpsObservabilityRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["resource"] = "" + request_init["parent"] = "" + request_init["data_source_type"] = "" request = request_type(**request_init) - pb_request = request + pb_request = request_type.pb(request) jsonified_request = json.loads( json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) @@ -7344,8 +8467,8 @@ def test_get_iam_policy_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetIamPolicy, - "_BaseGetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseSetAgentOpsObservability, + "_BaseSetAgentOpsObservability__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7355,11 +8478,14 @@ def test_get_iam_policy_rest_required_fields( # verify required fields with default values are now present - jsonified_request["resource"] = "resource_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["dataSourceType"] = "data_source_type_value" # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == "resource_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "dataSourceType" in jsonified_request + assert jsonified_request["dataSourceType"] == "data_source_type_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7368,7 +8494,7 @@ def test_get_iam_policy_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() + 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 @@ -7377,7 +8503,7 @@ def test_get_iam_policy_rest_required_fields( with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. - pb_request = request + pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", "method": "post", @@ -7388,21 +8514,20 @@ def test_get_iam_policy_rest_required_fields( response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_iam_policy(request) + response = client.set_agent_ops_observability(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_iam_policy_rest_flattened(): +def test_set_agent_ops_observability_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7411,16 +8536,16 @@ def test_get_iam_policy_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = { - "resource": "projects/sample1/locations/sample2/dataAgents/sample3" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - resource="resource_value", + parent="parent_value", + telemetry_enabled=True, + data_source_type="data_source_type_value", ) mock_args.update(sample_request) @@ -7432,20 +8557,20 @@ def test_get_iam_policy_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_iam_policy(**mock_args) + client.set_agent_ops_observability(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{resource=projects/*/locations/*/dataAgents/*}:getIamPolicy" + "%s/v1alpha/{parent=projects/*/locations/*}/observabilitySettings:setAgentOpsObservability" % client.transport._host, args[1], ) -def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): +def test_set_agent_ops_observability_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7454,13 +8579,15 @@ def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource="resource_value", + client.set_agent_ops_observability( + data_agent_service.SetAgentOpsObservabilityRequest(), + parent="parent_value", + telemetry_enabled=True, + data_source_type="data_source_type_value", ) -def test_set_iam_policy_rest_use_cached_wrapped_rpc(): +def test_retrieve_agent_ops_observability_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7474,46 +8601,53 @@ def test_set_iam_policy_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.set_iam_policy in client._transport._wrapped_methods + assert ( + client._transport.retrieve_agent_ops_observability + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.set_iam_policy] = mock_rpc + client._transport._wrapped_methods[ + client._transport.retrieve_agent_ops_observability + ] = mock_rpc request = {} - client.set_iam_policy(request) + client.retrieve_agent_ops_observability(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.set_iam_policy(request) + client.retrieve_agent_ops_observability(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_set_iam_policy_rest_required_fields( - request_type=iam_policy_pb2.SetIamPolicyRequest, +def test_retrieve_agent_ops_observability_rest_required_fields( + request_type=data_agent_service.RetrieveAgentOpsObservabilityRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["resource"] = "" + request_init["parent"] = "" + request_init["data_source_type"] = "" request = request_type(**request_init) - pb_request = request + pb_request = request_type.pb(request) jsonified_request = json.loads( json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) # verify fields with default values are dropped + assert "dataSourceType" not in jsonified_request default_values = getattr( - transport_class._BaseSetIamPolicy, - "_BaseSetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseRetrieveAgentOpsObservability, + "_BaseRetrieveAgentOpsObservability__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7522,12 +8656,20 @@ def test_set_iam_policy_rest_required_fields( jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "dataSourceType" in jsonified_request + assert jsonified_request["dataSourceType"] == request_init["data_source_type"] - jsonified_request["resource"] = "resource_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["dataSourceType"] = "data_source_type_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("dataSourceType",)) # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == "resource_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "dataSourceType" in jsonified_request + assert jsonified_request["dataSourceType"] == "data_source_type_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7536,7 +8678,7 @@ def test_set_iam_policy_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7545,32 +8687,41 @@ def test_set_iam_policy_rest_required_fields( with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. - pb_request = request + pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.set_iam_policy(request) + response = client.retrieve_agent_ops_observability(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "dataSourceType", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_set_iam_policy_rest_flattened(): +def test_retrieve_agent_ops_observability_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7579,41 +8730,44 @@ def test_set_iam_policy_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "resource": "projects/sample1/locations/sample2/dataAgents/sample3" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - resource="resource_value", + parent="parent_value", + data_source_type="data_source_type_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.set_iam_policy(**mock_args) + client.retrieve_agent_ops_observability(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{resource=projects/*/locations/*/dataAgents/*}:setIamPolicy" + "%s/v1alpha/{parent=projects/*/locations/*}:retrieveAgentOpsObservability" % client.transport._host, args[1], ) -def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): +def test_retrieve_agent_ops_observability_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7622,9 +8776,10 @@ def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource="resource_value", + client.retrieve_agent_ops_observability( + data_agent_service.RetrieveAgentOpsObservabilityRequest(), + parent="parent_value", + data_source_type="data_source_type_value", ) @@ -7968,6 +9123,50 @@ def test_set_iam_policy_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_agent_ops_observability_empty_call_grpc(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.set_agent_ops_observability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.SetAgentOpsObservabilityRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_retrieve_agent_ops_observability_empty_call_grpc(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + call.return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() + client.retrieve_agent_ops_observability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.RetrieveAgentOpsObservabilityRequest() + assert args[0] == request_msg + + def test_transport_kind_grpc_asyncio(): transport = DataAgentServiceAsyncClient.get_transport_class("grpc_asyncio")( credentials=async_anonymous_credentials() @@ -8055,6 +9254,8 @@ async def test_get_data_agent_empty_call_grpc_asyncio(): name="name_value", display_name="display_name_value", description="description_value", + kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) ) await client.get_data_agent(request=None) @@ -8111,6 +9312,8 @@ async def test_create_data_agent_sync_empty_call_grpc_asyncio(): name="name_value", display_name="display_name_value", description="description_value", + kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) ) await client.create_data_agent_sync(request=None) @@ -8167,6 +9370,8 @@ async def test_update_data_agent_sync_empty_call_grpc_asyncio(): name="name_value", display_name="display_name_value", description="description_value", + kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) ) await client.update_data_agent_sync(request=None) @@ -8282,6 +9487,65 @@ async def test_set_iam_policy_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_set_agent_ops_observability_empty_call_grpc_asyncio(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.set_agent_ops_observability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.SetAgentOpsObservabilityRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_retrieve_agent_ops_observability_empty_call_grpc_asyncio(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_agent_service.RetrieveAgentOpsObservabilityResponse( + telemetry_enabled=True, + bigquery_enabled=True, + cloud_trace_enabled=True, + cloud_monitoring_enabled=True, + cloud_logging_enabled=True, + bqaa_enabled=True, + ) + ) + await client.retrieve_agent_ops_observability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.RetrieveAgentOpsObservabilityRequest() + assert args[0] == request_msg + + def test_transport_kind_rest(): transport = DataAgentServiceClient.get_transport_class("rest")( credentials=ga_credentials.AnonymousCredentials() @@ -8618,6 +9882,8 @@ def test_get_data_agent_rest_call_success(request_type): name="name_value", display_name="display_name_value", description="description_value", + kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) # Wrap the value into a proper Response obj @@ -8637,6 +9903,8 @@ def test_get_data_agent_rest_call_success(request_type): assert response.name == "name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" + assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -8787,6 +10055,13 @@ def test_create_data_agent_rest_call_success(request_type): }, } ], + "property_graph_references": [ + { + "project_id": "project_id_value", + "dataset_id": "dataset_id_value", + "property_graph_id": "property_graph_id_value", + } + ], "agent_context_reference": { "context_set_id": "context_set_id_value" }, @@ -8882,11 +10157,19 @@ def test_create_data_agent_rest_call_success(request_type): "chart": {"image": {"no_image": {}, "svg": {}}}, "analysis": {"python": {"enabled": True}}, "datasource": {"big_query_max_billed_bytes": {"value": 541}}, + "model": 1, }, "example_queries": [ { "sql_query": "sql_query_value", "natural_language_question": "natural_language_question_value", + "parameters": [ + { + "name": "name_value", + "description": "description_value", + "data_type": "data_type_value", + } + ], } ], "looker_golden_queries": [ @@ -8904,6 +10187,27 @@ def test_create_data_agent_rest_call_success(request_type): ], "sorts": ["sorts_value1", "sorts_value2"], "limit": "limit_value", + "dynamic_fields": [ + { + "category": "category_value", + "name": "name_value", + "label": "label_value", + "based_on": "based_on_value", + "type_": "type__value", + "description": "description_value", + "expression": "expression_value", + "filter_expression": "filter_expression_value", + "value_format": "value_format_value", + "value_format_name": "value_format_name_value", + "calculation_type": "calculation_type_value", + "args": ["args_value1", "args_value2"], + "kind_hint": "kind_hint_value", + "type_hint": "type_hint_value", + "is_disabled": True, + } + ], + "query_id": "query_id_value", + "client_id": "client_id_value", }, } ], @@ -8925,6 +10229,18 @@ def test_create_data_agent_rest_call_success(request_type): "confidence_score": 0.1673, } ], + "user_functions": { + "bq_routines": [ + { + "routine_reference": { + "project_id": "project_id_value", + "dataset_id": "dataset_id_value", + "routine_id": "routine_id_value", + }, + "description": "description_value", + } + ] + }, }, "published_context": {}, "last_published_context": {}, @@ -8937,6 +10253,9 @@ def test_create_data_agent_rest_call_success(request_type): "update_time": {}, "delete_time": {}, "purge_time": {}, + "kms_key": "kms_key_value", + "bigquery_agent_analytics_enabled": True, + "bigquery_agent_analytics_table": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -9174,6 +10493,13 @@ def test_create_data_agent_sync_rest_call_success(request_type): }, } ], + "property_graph_references": [ + { + "project_id": "project_id_value", + "dataset_id": "dataset_id_value", + "property_graph_id": "property_graph_id_value", + } + ], "agent_context_reference": { "context_set_id": "context_set_id_value" }, @@ -9269,11 +10595,19 @@ def test_create_data_agent_sync_rest_call_success(request_type): "chart": {"image": {"no_image": {}, "svg": {}}}, "analysis": {"python": {"enabled": True}}, "datasource": {"big_query_max_billed_bytes": {"value": 541}}, + "model": 1, }, "example_queries": [ { "sql_query": "sql_query_value", "natural_language_question": "natural_language_question_value", + "parameters": [ + { + "name": "name_value", + "description": "description_value", + "data_type": "data_type_value", + } + ], } ], "looker_golden_queries": [ @@ -9291,6 +10625,27 @@ def test_create_data_agent_sync_rest_call_success(request_type): ], "sorts": ["sorts_value1", "sorts_value2"], "limit": "limit_value", + "dynamic_fields": [ + { + "category": "category_value", + "name": "name_value", + "label": "label_value", + "based_on": "based_on_value", + "type_": "type__value", + "description": "description_value", + "expression": "expression_value", + "filter_expression": "filter_expression_value", + "value_format": "value_format_value", + "value_format_name": "value_format_name_value", + "calculation_type": "calculation_type_value", + "args": ["args_value1", "args_value2"], + "kind_hint": "kind_hint_value", + "type_hint": "type_hint_value", + "is_disabled": True, + } + ], + "query_id": "query_id_value", + "client_id": "client_id_value", }, } ], @@ -9312,6 +10667,18 @@ def test_create_data_agent_sync_rest_call_success(request_type): "confidence_score": 0.1673, } ], + "user_functions": { + "bq_routines": [ + { + "routine_reference": { + "project_id": "project_id_value", + "dataset_id": "dataset_id_value", + "routine_id": "routine_id_value", + }, + "description": "description_value", + } + ] + }, }, "published_context": {}, "last_published_context": {}, @@ -9324,6 +10691,9 @@ def test_create_data_agent_sync_rest_call_success(request_type): "update_time": {}, "delete_time": {}, "purge_time": {}, + "kms_key": "kms_key_value", + "bigquery_agent_analytics_enabled": True, + "bigquery_agent_analytics_table": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -9401,6 +10771,8 @@ def get_message_fields(field): name="name_value", display_name="display_name_value", description="description_value", + kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) # Wrap the value into a proper Response obj @@ -9420,6 +10792,8 @@ def get_message_fields(field): assert response.name == "name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" + assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -9574,6 +10948,13 @@ def test_update_data_agent_rest_call_success(request_type): }, } ], + "property_graph_references": [ + { + "project_id": "project_id_value", + "dataset_id": "dataset_id_value", + "property_graph_id": "property_graph_id_value", + } + ], "agent_context_reference": { "context_set_id": "context_set_id_value" }, @@ -9669,11 +11050,19 @@ def test_update_data_agent_rest_call_success(request_type): "chart": {"image": {"no_image": {}, "svg": {}}}, "analysis": {"python": {"enabled": True}}, "datasource": {"big_query_max_billed_bytes": {"value": 541}}, + "model": 1, }, "example_queries": [ { "sql_query": "sql_query_value", "natural_language_question": "natural_language_question_value", + "parameters": [ + { + "name": "name_value", + "description": "description_value", + "data_type": "data_type_value", + } + ], } ], "looker_golden_queries": [ @@ -9691,6 +11080,27 @@ def test_update_data_agent_rest_call_success(request_type): ], "sorts": ["sorts_value1", "sorts_value2"], "limit": "limit_value", + "dynamic_fields": [ + { + "category": "category_value", + "name": "name_value", + "label": "label_value", + "based_on": "based_on_value", + "type_": "type__value", + "description": "description_value", + "expression": "expression_value", + "filter_expression": "filter_expression_value", + "value_format": "value_format_value", + "value_format_name": "value_format_name_value", + "calculation_type": "calculation_type_value", + "args": ["args_value1", "args_value2"], + "kind_hint": "kind_hint_value", + "type_hint": "type_hint_value", + "is_disabled": True, + } + ], + "query_id": "query_id_value", + "client_id": "client_id_value", }, } ], @@ -9712,6 +11122,18 @@ def test_update_data_agent_rest_call_success(request_type): "confidence_score": 0.1673, } ], + "user_functions": { + "bq_routines": [ + { + "routine_reference": { + "project_id": "project_id_value", + "dataset_id": "dataset_id_value", + "routine_id": "routine_id_value", + }, + "description": "description_value", + } + ] + }, }, "published_context": {}, "last_published_context": {}, @@ -9724,6 +11146,9 @@ def test_update_data_agent_rest_call_success(request_type): "update_time": {}, "delete_time": {}, "purge_time": {}, + "kms_key": "kms_key_value", + "bigquery_agent_analytics_enabled": True, + "bigquery_agent_analytics_table": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -9965,6 +11390,13 @@ def test_update_data_agent_sync_rest_call_success(request_type): }, } ], + "property_graph_references": [ + { + "project_id": "project_id_value", + "dataset_id": "dataset_id_value", + "property_graph_id": "property_graph_id_value", + } + ], "agent_context_reference": { "context_set_id": "context_set_id_value" }, @@ -10060,11 +11492,19 @@ def test_update_data_agent_sync_rest_call_success(request_type): "chart": {"image": {"no_image": {}, "svg": {}}}, "analysis": {"python": {"enabled": True}}, "datasource": {"big_query_max_billed_bytes": {"value": 541}}, + "model": 1, }, "example_queries": [ { "sql_query": "sql_query_value", "natural_language_question": "natural_language_question_value", + "parameters": [ + { + "name": "name_value", + "description": "description_value", + "data_type": "data_type_value", + } + ], } ], "looker_golden_queries": [ @@ -10082,6 +11522,27 @@ def test_update_data_agent_sync_rest_call_success(request_type): ], "sorts": ["sorts_value1", "sorts_value2"], "limit": "limit_value", + "dynamic_fields": [ + { + "category": "category_value", + "name": "name_value", + "label": "label_value", + "based_on": "based_on_value", + "type_": "type__value", + "description": "description_value", + "expression": "expression_value", + "filter_expression": "filter_expression_value", + "value_format": "value_format_value", + "value_format_name": "value_format_name_value", + "calculation_type": "calculation_type_value", + "args": ["args_value1", "args_value2"], + "kind_hint": "kind_hint_value", + "type_hint": "type_hint_value", + "is_disabled": True, + } + ], + "query_id": "query_id_value", + "client_id": "client_id_value", }, } ], @@ -10103,6 +11564,18 @@ def test_update_data_agent_sync_rest_call_success(request_type): "confidence_score": 0.1673, } ], + "user_functions": { + "bq_routines": [ + { + "routine_reference": { + "project_id": "project_id_value", + "dataset_id": "dataset_id_value", + "routine_id": "routine_id_value", + }, + "description": "description_value", + } + ] + }, }, "published_context": {}, "last_published_context": {}, @@ -10115,6 +11588,9 @@ def test_update_data_agent_sync_rest_call_success(request_type): "update_time": {}, "delete_time": {}, "purge_time": {}, + "kms_key": "kms_key_value", + "bigquery_agent_analytics_enabled": True, + "bigquery_agent_analytics_table": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -10192,6 +11668,8 @@ def get_message_fields(field): name="name_value", display_name="display_name_value", description="description_value", + kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) # Wrap the value into a proper Response obj @@ -10211,6 +11689,8 @@ def get_message_fields(field): assert response.name == "name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" + assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -10234,14 +11714,256 @@ def test_update_data_agent_sync_rest_interceptors(null_interceptor): "post_update_data_agent_sync_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DataAgentServiceRestInterceptor, "pre_update_data_agent_sync" + transports.DataAgentServiceRestInterceptor, "pre_update_data_agent_sync" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = data_agent_service.UpdateDataAgentRequest.pb( + data_agent_service.UpdateDataAgentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcg_data_agent.DataAgent.to_json(gcg_data_agent.DataAgent()) + req.return_value.content = return_value + + request = data_agent_service.UpdateDataAgentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcg_data_agent.DataAgent() + post_with_metadata.return_value = gcg_data_agent.DataAgent(), metadata + + client.update_data_agent_sync( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_data_agent_rest_bad_request( + request_type=data_agent_service.DeleteDataAgentRequest, +): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/dataAgents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_data_agent(request) + + +@pytest.mark.parametrize( + "request_type", + [ + data_agent_service.DeleteDataAgentRequest, + dict, + ], +) +def test_delete_data_agent_rest_call_success(request_type): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/dataAgents/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 = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_data_agent(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_data_agent_rest_interceptors(null_interceptor): + transport = transports.DataAgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DataAgentServiceRestInterceptor(), + ) + client = DataAgentServiceClient(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.DataAgentServiceRestInterceptor, "post_delete_data_agent" + ) as post, + mock.patch.object( + transports.DataAgentServiceRestInterceptor, + "post_delete_data_agent_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DataAgentServiceRestInterceptor, "pre_delete_data_agent" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = data_agent_service.DeleteDataAgentRequest.pb( + data_agent_service.DeleteDataAgentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = data_agent_service.DeleteDataAgentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_data_agent( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_data_agent_sync_rest_bad_request( + request_type=data_agent_service.DeleteDataAgentRequest, +): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/dataAgents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_data_agent_sync(request) + + +@pytest.mark.parametrize( + "request_type", + [ + data_agent_service.DeleteDataAgentRequest, + dict, + ], +) +def test_delete_data_agent_sync_rest_call_success(request_type): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/dataAgents/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 = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_data_agent_sync(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_data_agent_sync_rest_interceptors(null_interceptor): + transport = transports.DataAgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DataAgentServiceRestInterceptor(), + ) + client = DataAgentServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DataAgentServiceRestInterceptor, "pre_delete_data_agent_sync" ) as pre, ): pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = data_agent_service.UpdateDataAgentRequest.pb( - data_agent_service.UpdateDataAgentRequest() + pb_message = data_agent_service.DeleteDataAgentRequest.pb( + data_agent_service.DeleteDataAgentRequest() ) transcode.return_value = { "method": "post", @@ -10253,19 +11975,15 @@ def test_update_data_agent_sync_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = gcg_data_agent.DataAgent.to_json(gcg_data_agent.DataAgent()) - req.return_value.content = return_value - request = data_agent_service.UpdateDataAgentRequest() + request = data_agent_service.DeleteDataAgentRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gcg_data_agent.DataAgent() - post_with_metadata.return_value = gcg_data_agent.DataAgent(), metadata - client.update_data_agent_sync( + client.delete_data_agent_sync( request, metadata=[ ("key", "val"), @@ -10274,18 +11992,16 @@ def test_update_data_agent_sync_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() -def test_delete_data_agent_rest_bad_request( - request_type=data_agent_service.DeleteDataAgentRequest, +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, ): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/dataAgents/sample3"} + request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10301,29 +12017,32 @@ def test_delete_data_agent_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_data_agent(request) + client.get_iam_policy(request) @pytest.mark.parametrize( "request_type", [ - data_agent_service.DeleteDataAgentRequest, + iam_policy_pb2.GetIamPolicyRequest, dict, ], ) -def test_delete_data_agent_rest_call_success(request_type): +def test_get_iam_policy_rest_call_success(request_type): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/dataAgents/sample3"} + request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -10332,14 +12051,16 @@ def test_delete_data_agent_rest_call_success(request_type): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_data_agent(request) + response = client.get_iam_policy(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_data_agent_rest_interceptors(null_interceptor): +def test_get_iam_policy_rest_interceptors(null_interceptor): transport = transports.DataAgentServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10351,24 +12072,21 @@ def test_delete_data_agent_rest_interceptors(null_interceptor): 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.DataAgentServiceRestInterceptor, "post_delete_data_agent" + transports.DataAgentServiceRestInterceptor, "post_get_iam_policy" ) as post, mock.patch.object( transports.DataAgentServiceRestInterceptor, - "post_delete_data_agent_with_metadata", + "post_get_iam_policy_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DataAgentServiceRestInterceptor, "pre_delete_data_agent" + transports.DataAgentServiceRestInterceptor, "pre_get_iam_policy" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = data_agent_service.DeleteDataAgentRequest.pb( - data_agent_service.DeleteDataAgentRequest() - ) + pb_message = iam_policy_pb2.GetIamPolicyRequest() transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10379,19 +12097,19 @@ def test_delete_data_agent_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) + return_value = json_format.MessageToJson(policy_pb2.Policy()) req.return_value.content = return_value - request = data_agent_service.DeleteDataAgentRequest() + request = iam_policy_pb2.GetIamPolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + post.return_value = policy_pb2.Policy() + post_with_metadata.return_value = policy_pb2.Policy(), metadata - client.delete_data_agent( + client.get_iam_policy( request, metadata=[ ("key", "val"), @@ -10404,14 +12122,14 @@ def test_delete_data_agent_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_data_agent_sync_rest_bad_request( - request_type=data_agent_service.DeleteDataAgentRequest, +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, ): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/dataAgents/sample3"} + request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10427,45 +12145,50 @@ def test_delete_data_agent_sync_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_data_agent_sync(request) + client.set_iam_policy(request) @pytest.mark.parametrize( "request_type", [ - data_agent_service.DeleteDataAgentRequest, + iam_policy_pb2.SetIamPolicyRequest, dict, ], ) -def test_delete_data_agent_sync_rest_call_success(request_type): +def test_set_iam_policy_rest_call_success(request_type): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/dataAgents/sample3"} + request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/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 + return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" + json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_data_agent_sync(request) + response = client.set_iam_policy(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_data_agent_sync_rest_interceptors(null_interceptor): +def test_set_iam_policy_rest_interceptors(null_interceptor): transport = transports.DataAgentServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10478,13 +12201,20 @@ def test_delete_data_agent_sync_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.DataAgentServiceRestInterceptor, "pre_delete_data_agent_sync" + transports.DataAgentServiceRestInterceptor, "post_set_iam_policy" + ) as post, + mock.patch.object( + transports.DataAgentServiceRestInterceptor, + "post_set_iam_policy_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DataAgentServiceRestInterceptor, "pre_set_iam_policy" ) as pre, ): pre.assert_not_called() - pb_message = data_agent_service.DeleteDataAgentRequest.pb( - data_agent_service.DeleteDataAgentRequest() - ) + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10495,15 +12225,19 @@ def test_delete_data_agent_sync_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(policy_pb2.Policy()) + req.return_value.content = return_value - request = data_agent_service.DeleteDataAgentRequest() + request = iam_policy_pb2.SetIamPolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + post_with_metadata.return_value = policy_pb2.Policy(), metadata - client.delete_data_agent_sync( + client.set_iam_policy( request, metadata=[ ("key", "val"), @@ -10512,16 +12246,18 @@ def test_delete_data_agent_sync_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_get_iam_policy_rest_bad_request( - request_type=iam_policy_pb2.GetIamPolicyRequest, +def test_set_agent_ops_observability_rest_bad_request( + request_type=data_agent_service.SetAgentOpsObservabilityRequest, ): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} + 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. @@ -10537,32 +12273,29 @@ def test_get_iam_policy_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_iam_policy(request) + client.set_agent_ops_observability(request) @pytest.mark.parametrize( "request_type", [ - iam_policy_pb2.GetIamPolicyRequest, + data_agent_service.SetAgentOpsObservabilityRequest, dict, ], ) -def test_get_iam_policy_rest_call_success(request_type): +def test_set_agent_ops_observability_rest_call_success(request_type): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} + 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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -10571,16 +12304,14 @@ def test_get_iam_policy_rest_call_success(request_type): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_iam_policy(request) + response = client.set_agent_ops_observability(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" + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): +def test_set_agent_ops_observability_rest_interceptors(null_interceptor): transport = transports.DataAgentServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10592,21 +12323,26 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): 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.DataAgentServiceRestInterceptor, "post_get_iam_policy" + transports.DataAgentServiceRestInterceptor, + "post_set_agent_ops_observability", ) as post, mock.patch.object( transports.DataAgentServiceRestInterceptor, - "post_get_iam_policy_with_metadata", + "post_set_agent_ops_observability_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DataAgentServiceRestInterceptor, "pre_get_iam_policy" + transports.DataAgentServiceRestInterceptor, + "pre_set_agent_ops_observability", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() + pb_message = data_agent_service.SetAgentOpsObservabilityRequest.pb( + data_agent_service.SetAgentOpsObservabilityRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10617,19 +12353,19 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(policy_pb2.Policy()) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = iam_policy_pb2.GetIamPolicyRequest() + request = data_agent_service.SetAgentOpsObservabilityRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - post_with_metadata.return_value = policy_pb2.Policy(), metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.get_iam_policy( + client.set_agent_ops_observability( request, metadata=[ ("key", "val"), @@ -10642,14 +12378,14 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_set_iam_policy_rest_bad_request( - request_type=iam_policy_pb2.SetIamPolicyRequest, +def test_retrieve_agent_ops_observability_rest_bad_request( + request_type=data_agent_service.RetrieveAgentOpsObservabilityRequest, ): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} + 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. @@ -10665,50 +12401,65 @@ def test_set_iam_policy_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.set_iam_policy(request) + client.retrieve_agent_ops_observability(request) @pytest.mark.parametrize( "request_type", [ - iam_policy_pb2.SetIamPolicyRequest, + data_agent_service.RetrieveAgentOpsObservabilityRequest, dict, ], ) -def test_set_iam_policy_rest_call_success(request_type): +def test_retrieve_agent_ops_observability_rest_call_success(request_type): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} + 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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse( + telemetry_enabled=True, + bigquery_enabled=True, + cloud_trace_enabled=True, + cloud_monitoring_enabled=True, + cloud_logging_enabled=True, + bqaa_enabled=True, ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.set_iam_policy(request) + response = client.retrieve_agent_ops_observability(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" + assert isinstance( + response, data_agent_service.RetrieveAgentOpsObservabilityResponse + ) + assert response.telemetry_enabled is True + assert response.bigquery_enabled is True + assert response.cloud_trace_enabled is True + assert response.cloud_monitoring_enabled is True + assert response.cloud_logging_enabled is True + assert response.bqaa_enabled is True @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): +def test_retrieve_agent_ops_observability_rest_interceptors(null_interceptor): transport = transports.DataAgentServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10721,20 +12472,24 @@ def test_set_iam_policy_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.DataAgentServiceRestInterceptor, "post_set_iam_policy" + transports.DataAgentServiceRestInterceptor, + "post_retrieve_agent_ops_observability", ) as post, mock.patch.object( transports.DataAgentServiceRestInterceptor, - "post_set_iam_policy_with_metadata", + "post_retrieve_agent_ops_observability_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DataAgentServiceRestInterceptor, "pre_set_iam_policy" + transports.DataAgentServiceRestInterceptor, + "pre_retrieve_agent_ops_observability", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() + pb_message = data_agent_service.RetrieveAgentOpsObservabilityRequest.pb( + data_agent_service.RetrieveAgentOpsObservabilityRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10745,19 +12500,24 @@ def test_set_iam_policy_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(policy_pb2.Policy()) + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse.to_json( + data_agent_service.RetrieveAgentOpsObservabilityResponse() + ) req.return_value.content = return_value - request = iam_policy_pb2.SetIamPolicyRequest() + request = data_agent_service.RetrieveAgentOpsObservabilityRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - post_with_metadata.return_value = policy_pb2.Policy(), metadata + post.return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() + post_with_metadata.return_value = ( + data_agent_service.RetrieveAgentOpsObservabilityResponse(), + metadata, + ) - client.set_iam_policy( + client.retrieve_agent_ops_observability( request, metadata=[ ("key", "val"), @@ -11374,6 +13134,48 @@ def test_set_iam_policy_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_agent_ops_observability_empty_call_rest(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + client.set_agent_ops_observability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.SetAgentOpsObservabilityRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_retrieve_agent_ops_observability_empty_call_rest(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + client.retrieve_agent_ops_observability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.RetrieveAgentOpsObservabilityRequest() + assert args[0] == request_msg + + def test_data_agent_service_rest_lro_client(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11435,6 +13237,8 @@ def test_data_agent_service_base_transport(): "delete_data_agent_sync", "get_iam_policy", "set_iam_policy", + "set_agent_ops_observability", + "retrieve_agent_ops_observability", "get_location", "list_locations", "get_operation", @@ -11744,6 +13548,12 @@ def test_data_agent_service_client_transport_session_collision(transport_name): session1 = client1.transport.set_iam_policy._session session2 = client2.transport.set_iam_policy._session assert session1 != session2 + session1 = client1.transport.set_agent_ops_observability._session + session2 = client2.transport.set_agent_ops_observability._session + assert session1 != session2 + session1 = client1.transport.retrieve_agent_ops_observability._session + session2 = client2.transport.retrieve_agent_ops_observability._session + assert session1 != session2 def test_data_agent_service_grpc_transport_channel(): @@ -11907,10 +13717,41 @@ def test_data_agent_service_grpc_lro_async_client(): assert transport.operations_client is transport.operations_client -def test_data_agent_path(): +def test_crypto_key_path(): project = "squid" location = "clam" - data_agent = "whelk" + key_ring = "whelk" + crypto_key = "octopus" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + ) + actual = DataAgentServiceClient.crypto_key_path( + project, location, key_ring, crypto_key + ) + assert expected == actual + + +def test_parse_crypto_key_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "key_ring": "cuttlefish", + "crypto_key": "mussel", + } + path = DataAgentServiceClient.crypto_key_path(**expected) + + # Check that the path construction is reversible. + actual = DataAgentServiceClient.parse_crypto_key_path(path) + assert expected == actual + + +def test_data_agent_path(): + project = "winkle" + location = "nautilus" + data_agent = "scallop" expected = "projects/{project}/locations/{location}/dataAgents/{data_agent}".format( project=project, location=location, @@ -11922,9 +13763,9 @@ def test_data_agent_path(): def test_parse_data_agent_path(): expected = { - "project": "octopus", - "location": "oyster", - "data_agent": "nudibranch", + "project": "abalone", + "location": "squid", + "data_agent": "clam", } path = DataAgentServiceClient.data_agent_path(**expected) @@ -11934,7 +13775,7 @@ def test_parse_data_agent_path(): def test_common_billing_account_path(): - billing_account = "cuttlefish" + billing_account = "whelk" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -11944,7 +13785,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "mussel", + "billing_account": "octopus", } path = DataAgentServiceClient.common_billing_account_path(**expected) @@ -11954,7 +13795,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "winkle" + folder = "oyster" expected = "folders/{folder}".format( folder=folder, ) @@ -11964,7 +13805,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nautilus", + "folder": "nudibranch", } path = DataAgentServiceClient.common_folder_path(**expected) @@ -11974,7 +13815,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "scallop" + organization = "cuttlefish" expected = "organizations/{organization}".format( organization=organization, ) @@ -11984,7 +13825,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "abalone", + "organization": "mussel", } path = DataAgentServiceClient.common_organization_path(**expected) @@ -11994,7 +13835,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "squid" + project = "winkle" expected = "projects/{project}".format( project=project, ) @@ -12004,7 +13845,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "clam", + "project": "nautilus", } path = DataAgentServiceClient.common_project_path(**expected) @@ -12014,8 +13855,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "whelk" - location = "octopus" + project = "scallop" + location = "abalone" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -12026,8 +13867,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "oyster", - "location": "nudibranch", + "project": "squid", + "location": "clam", } path = DataAgentServiceClient.common_location_path(**expected) diff --git a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_chat_service.py b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_chat_service.py index b71a382aeca5..24f1e05efc0e 100644 --- a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_chat_service.py +++ b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_chat_service.py @@ -39,6 +39,7 @@ HAS_GOOGLE_AUTH_AIO = False import google.auth +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.struct_pb2 as struct_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import google.protobuf.wrappers_pb2 as wrappers_pb2 # type: ignore @@ -70,6 +71,7 @@ credentials, data_chat_service, datasource, + usage, ) from google.cloud.geminidataanalytics_v1alpha.types import ( conversation as gcg_conversation, @@ -1359,6 +1361,8 @@ def test_create_conversation(request_type, transport: str = "grpc"): call.return_value = gcg_conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", ) response = client.create_conversation(request) @@ -1372,6 +1376,8 @@ def test_create_conversation(request_type, transport: str = "grpc"): assert isinstance(response, gcg_conversation.Conversation) assert response.name == "name_value" assert response.agents == ["agents_value"] + assert response.title == "title_value" + assert response.kms_key == "kms_key_value" def test_create_conversation_non_empty_request_with_auto_populated_field(): @@ -1515,6 +1521,8 @@ async def test_create_conversation_async(request_type, transport: str = "grpc_as gcg_conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", ) ) response = await client.create_conversation(request) @@ -1529,6 +1537,8 @@ async def test_create_conversation_async(request_type, transport: str = "grpc_as assert isinstance(response, gcg_conversation.Conversation) assert response.name == "name_value" assert response.agents == ["agents_value"] + assert response.title == "title_value" + assert response.kms_key == "kms_key_value" def test_create_conversation_field_headers(): @@ -2032,6 +2042,366 @@ async def test_delete_conversation_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + gcg_conversation.UpdateConversationRequest(), + {}, + ], +) +def test_update_conversation(request_type, transport: str = "grpc"): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcg_conversation.Conversation( + name="name_value", + agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", + ) + response = client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcg_conversation.UpdateConversationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcg_conversation.Conversation) + assert response.name == "name_value" + assert response.agents == ["agents_value"] + assert response.title == "title_value" + assert response.kms_key == "kms_key_value" + + +def test_update_conversation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcg_conversation.UpdateConversationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_conversation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcg_conversation.UpdateConversationRequest() + assert args[0] == request_msg + + +def test_update_conversation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_conversation in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_conversation] = ( + mock_rpc + ) + request = {} + client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_conversation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_conversation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DataChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_conversation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_conversation + ] = mock_rpc + + request = {} + await client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_conversation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + gcg_conversation.UpdateConversationRequest(), + {}, + ], +) +async def test_update_conversation_async(request_type, transport: str = "grpc_asyncio"): + client = DataChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcg_conversation.Conversation( + name="name_value", + agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", + ) + ) + response = await client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcg_conversation.UpdateConversationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcg_conversation.Conversation) + assert response.name == "name_value" + assert response.agents == ["agents_value"] + assert response.title == "title_value" + assert response.kms_key == "kms_key_value" + + +def test_update_conversation_field_headers(): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcg_conversation.UpdateConversationRequest() + + request.conversation.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + call.return_value = gcg_conversation.Conversation() + client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "conversation.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_conversation_field_headers_async(): + client = DataChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcg_conversation.UpdateConversationRequest() + + request.conversation.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcg_conversation.Conversation() + ) + await client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "conversation.name=name_value", + ) in kw["metadata"] + + +def test_update_conversation_flattened(): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcg_conversation.Conversation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_conversation( + conversation=gcg_conversation.Conversation(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].conversation + mock_val = gcg_conversation.Conversation(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_conversation_flattened_error(): + client = DataChatServiceClient( + credentials=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_conversation( + gcg_conversation.UpdateConversationRequest(), + conversation=gcg_conversation.Conversation(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_conversation_flattened_async(): + client = DataChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcg_conversation.Conversation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcg_conversation.Conversation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_conversation( + conversation=gcg_conversation.Conversation(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].conversation + mock_val = gcg_conversation.Conversation(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_conversation_flattened_error_async(): + client = DataChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_conversation( + gcg_conversation.UpdateConversationRequest(), + conversation=gcg_conversation.Conversation(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + @pytest.mark.parametrize( "request_type", [ @@ -2055,6 +2425,8 @@ def test_get_conversation(request_type, transport: str = "grpc"): call.return_value = conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", ) response = client.get_conversation(request) @@ -2068,6 +2440,8 @@ def test_get_conversation(request_type, transport: str = "grpc"): assert isinstance(response, conversation.Conversation) assert response.name == "name_value" assert response.agents == ["agents_value"] + assert response.title == "title_value" + assert response.kms_key == "kms_key_value" def test_get_conversation_non_empty_request_with_auto_populated_field(): @@ -2203,6 +2577,8 @@ async def test_get_conversation_async(request_type, transport: str = "grpc_async conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", ) ) response = await client.get_conversation(request) @@ -2217,6 +2593,8 @@ async def test_get_conversation_async(request_type, transport: str = "grpc_async assert isinstance(response, conversation.Conversation) assert response.name == "name_value" assert response.agents == ["agents_value"] + assert response.title == "title_value" + assert response.kms_key == "kms_key_value" def test_get_conversation_field_headers(): @@ -4157,6 +4535,189 @@ def test_delete_conversation_rest_flattened_error(transport: str = "rest"): ) +def test_update_conversation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_conversation in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_conversation] = ( + mock_rpc + ) + + request = {} + client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_conversation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_conversation_rest_required_fields( + request_type=gcg_conversation.UpdateConversationRequest, +): + transport_class = transports.DataChatServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateConversation, + "_BaseUpdateConversation__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcg_conversation.Conversation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcg_conversation.Conversation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_conversation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_conversation_rest_flattened(): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcg_conversation.Conversation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "conversation": { + "name": "projects/sample1/locations/sample2/conversations/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + conversation=gcg_conversation.Conversation(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcg_conversation.Conversation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_conversation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{conversation.name=projects/*/locations/*/conversations/*}" + % client.transport._host, + args[1], + ) + + +def test_update_conversation_rest_flattened_error(transport: str = "rest"): + client = DataChatServiceClient( + credentials=ga_credentials.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_conversation( + gcg_conversation.UpdateConversationRequest(), + conversation=gcg_conversation.Conversation(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + def test_get_conversation_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5112,6 +5673,28 @@ def test_delete_conversation_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_conversation_empty_call_grpc(): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + call.return_value = gcg_conversation.Conversation() + client.update_conversation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcg_conversation.UpdateConversationRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_get_conversation_empty_call_grpc(): @@ -5251,6 +5834,8 @@ async def test_create_conversation_empty_call_grpc_asyncio(): gcg_conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", ) ) await client.create_conversation(request=None) @@ -5258,14 +5843,38 @@ async def test_create_conversation_empty_call_grpc_asyncio(): # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = gcg_conversation.CreateConversationRequest() + request_msg = gcg_conversation.CreateConversationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_conversation_empty_call_grpc_asyncio(): + client = DataChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_conversation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversation.DeleteConversationRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_delete_conversation_empty_call_grpc_asyncio(): +async def test_update_conversation_empty_call_grpc_asyncio(): client = DataChatServiceAsyncClient( credentials=async_anonymous_credentials(), transport="grpc_asyncio", @@ -5273,16 +5882,23 @@ async def test_delete_conversation_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_conversation), "__call__" + type(client.transport.update_conversation), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_conversation(request=None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcg_conversation.Conversation( + name="name_value", + agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", + ) + ) + await client.update_conversation(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = conversation.DeleteConversationRequest() + request_msg = gcg_conversation.UpdateConversationRequest() assert args[0] == request_msg @@ -5302,6 +5918,8 @@ async def test_get_conversation_empty_call_grpc_asyncio(): conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", ) ) await client.get_conversation(request=None) @@ -5577,6 +6195,8 @@ def test_create_conversation_rest_call_success(request_type): "create_time": {"seconds": 751, "nanos": 543}, "last_used_time": {}, "labels": {}, + "title": "title_value", + "kms_key": "kms_key_value", } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -5653,6 +6273,8 @@ def get_message_fields(field): return_value = gcg_conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", ) # Wrap the value into a proper Response obj @@ -5671,6 +6293,8 @@ def get_message_fields(field): assert isinstance(response, gcg_conversation.Conversation) assert response.name == "name_value" assert response.agents == ["agents_value"] + assert response.title == "title_value" + assert response.kms_key == "kms_key_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -5850,6 +6474,229 @@ def test_delete_conversation_rest_interceptors(null_interceptor): pre.assert_called_once() +def test_update_conversation_rest_bad_request( + request_type=gcg_conversation.UpdateConversationRequest, +): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "conversation": { + "name": "projects/sample1/locations/sample2/conversations/sample3" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_conversation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcg_conversation.UpdateConversationRequest, + dict, + ], +) +def test_update_conversation_rest_call_success(request_type): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "conversation": { + "name": "projects/sample1/locations/sample2/conversations/sample3" + } + } + request_init["conversation"] = { + "name": "projects/sample1/locations/sample2/conversations/sample3", + "agents": ["agents_value1", "agents_value2"], + "create_time": {"seconds": 751, "nanos": 543}, + "last_used_time": {}, + "labels": {}, + "title": "title_value", + "kms_key": "kms_key_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcg_conversation.UpdateConversationRequest.meta.fields["conversation"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["conversation"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["conversation"][field])): + del request_init["conversation"][field][i][subfield] + else: + del request_init["conversation"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcg_conversation.Conversation( + name="name_value", + agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcg_conversation.Conversation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_conversation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcg_conversation.Conversation) + assert response.name == "name_value" + assert response.agents == ["agents_value"] + assert response.title == "title_value" + assert response.kms_key == "kms_key_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_conversation_rest_interceptors(null_interceptor): + transport = transports.DataChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DataChatServiceRestInterceptor(), + ) + client = DataChatServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DataChatServiceRestInterceptor, "post_update_conversation" + ) as post, + mock.patch.object( + transports.DataChatServiceRestInterceptor, + "post_update_conversation_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DataChatServiceRestInterceptor, "pre_update_conversation" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcg_conversation.UpdateConversationRequest.pb( + gcg_conversation.UpdateConversationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcg_conversation.Conversation.to_json( + gcg_conversation.Conversation() + ) + req.return_value.content = return_value + + request = gcg_conversation.UpdateConversationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcg_conversation.Conversation() + post_with_metadata.return_value = gcg_conversation.Conversation(), metadata + + client.update_conversation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_get_conversation_rest_bad_request( request_type=conversation.GetConversationRequest, ): @@ -5898,6 +6745,8 @@ def test_get_conversation_rest_call_success(request_type): return_value = conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", ) # Wrap the value into a proper Response obj @@ -5916,6 +6765,8 @@ def test_get_conversation_rest_call_success(request_type): assert isinstance(response, conversation.Conversation) assert response.name == "name_value" assert response.agents == ["agents_value"] + assert response.title == "title_value" + assert response.kms_key == "kms_key_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -6840,6 +7691,27 @@ def test_delete_conversation_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_conversation_empty_call_rest(): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + client.update_conversation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcg_conversation.UpdateConversationRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_get_conversation_empty_call_rest(): @@ -6954,6 +7826,7 @@ def test_data_chat_service_base_transport(): "chat", "create_conversation", "delete_conversation", + "update_conversation", "get_conversation", "list_conversations", "list_messages", @@ -7238,6 +8111,9 @@ def test_data_chat_service_client_transport_session_collision(transport_name): session1 = client1.transport.delete_conversation._session session2 = client2.transport.delete_conversation._session assert session1 != session2 + session1 = client1.transport.update_conversation._session + session2 = client2.transport.update_conversation._session + assert session1 != session2 session1 = client1.transport.get_conversation._session session2 = client2.transport.get_conversation._session assert session1 != session2 @@ -7407,10 +8283,41 @@ def test_parse_conversation_path(): assert expected == actual -def test_data_agent_path(): +def test_crypto_key_path(): project = "cuttlefish" location = "mussel" - data_agent = "winkle" + key_ring = "winkle" + crypto_key = "nautilus" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + ) + actual = DataChatServiceClient.crypto_key_path( + project, location, key_ring, crypto_key + ) + assert expected == actual + + +def test_parse_crypto_key_path(): + expected = { + "project": "scallop", + "location": "abalone", + "key_ring": "squid", + "crypto_key": "clam", + } + path = DataChatServiceClient.crypto_key_path(**expected) + + # Check that the path construction is reversible. + actual = DataChatServiceClient.parse_crypto_key_path(path) + assert expected == actual + + +def test_data_agent_path(): + project = "whelk" + location = "octopus" + data_agent = "oyster" expected = "projects/{project}/locations/{location}/dataAgents/{data_agent}".format( project=project, location=location, @@ -7422,9 +8329,9 @@ def test_data_agent_path(): def test_parse_data_agent_path(): expected = { - "project": "nautilus", - "location": "scallop", - "data_agent": "abalone", + "project": "nudibranch", + "location": "cuttlefish", + "data_agent": "mussel", } path = DataChatServiceClient.data_agent_path(**expected) @@ -7434,7 +8341,7 @@ def test_parse_data_agent_path(): def test_common_billing_account_path(): - billing_account = "squid" + billing_account = "winkle" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -7444,7 +8351,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "clam", + "billing_account": "nautilus", } path = DataChatServiceClient.common_billing_account_path(**expected) @@ -7454,7 +8361,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "whelk" + folder = "scallop" expected = "folders/{folder}".format( folder=folder, ) @@ -7464,7 +8371,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "octopus", + "folder": "abalone", } path = DataChatServiceClient.common_folder_path(**expected) @@ -7474,7 +8381,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "oyster" + organization = "squid" expected = "organizations/{organization}".format( organization=organization, ) @@ -7484,7 +8391,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nudibranch", + "organization": "clam", } path = DataChatServiceClient.common_organization_path(**expected) @@ -7494,7 +8401,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "cuttlefish" + project = "whelk" expected = "projects/{project}".format( project=project, ) @@ -7504,7 +8411,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "mussel", + "project": "octopus", } path = DataChatServiceClient.common_project_path(**expected) @@ -7514,8 +8421,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "winkle" - location = "nautilus" + project = "oyster" + location = "nudibranch" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -7526,8 +8433,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "scallop", - "location": "abalone", + "project": "cuttlefish", + "location": "mussel", } path = DataChatServiceClient.common_location_path(**expected) diff --git a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_a2a_service.py b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_a2a_service.py new file mode 100644 index 000000000000..63029479f436 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_a2a_service.py @@ -0,0 +1,5389 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.auth +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account + +from google.cloud.geminidataanalytics_v1beta.services.data_a2a_service import ( + DataA2AServiceAsyncClient, + DataA2AServiceClient, + transports, +) +from google.cloud.geminidataanalytics_v1beta.types import data_a2a_service + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +@pytest.fixture(autouse=True) +def disable_mtls_env(): + with mock.patch.dict( + os.environ, + { + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", + "CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE": "false", + }, + ): + yield + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert DataA2AServiceClient._get_client_cert_source(None, False) is None + assert ( + DataA2AServiceClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + DataA2AServiceClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + DataA2AServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + DataA2AServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = DataA2AServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = DataA2AServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (DataA2AServiceClient, "grpc"), + (DataA2AServiceAsyncClient, "grpc_asyncio"), + (DataA2AServiceClient, "rest"), + ], +) +def test_data_a2a_service_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "geminidataanalytics.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://geminidataanalytics.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.DataA2AServiceGrpcTransport, "grpc"), + (transports.DataA2AServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DataA2AServiceRestTransport, "rest"), + ], +) +def test_data_a2a_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (DataA2AServiceClient, "grpc"), + (DataA2AServiceAsyncClient, "grpc_asyncio"), + (DataA2AServiceClient, "rest"), + ], +) +def test_data_a2a_service_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "geminidataanalytics.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://geminidataanalytics.googleapis.com" + ) + + +def test_data_a2a_service_client_get_transport_class(): + transport = DataA2AServiceClient.get_transport_class() + available_transports = [ + transports.DataA2AServiceGrpcTransport, + transports.DataA2AServiceRestTransport, + ] + assert transport in available_transports + + transport = DataA2AServiceClient.get_transport_class("grpc") + assert transport == transports.DataA2AServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (DataA2AServiceClient, transports.DataA2AServiceGrpcTransport, "grpc"), + ( + DataA2AServiceAsyncClient, + transports.DataA2AServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (DataA2AServiceClient, transports.DataA2AServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + DataA2AServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DataA2AServiceClient), +) +@mock.patch.object( + DataA2AServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DataA2AServiceAsyncClient), +) +def test_data_a2a_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(DataA2AServiceClient, "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(DataA2AServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (DataA2AServiceClient, transports.DataA2AServiceGrpcTransport, "grpc", "true"), + ( + DataA2AServiceAsyncClient, + transports.DataA2AServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (DataA2AServiceClient, transports.DataA2AServiceGrpcTransport, "grpc", "false"), + ( + DataA2AServiceAsyncClient, + transports.DataA2AServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (DataA2AServiceClient, transports.DataA2AServiceRestTransport, "rest", "true"), + (DataA2AServiceClient, transports.DataA2AServiceRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + DataA2AServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DataA2AServiceClient), +) +@mock.patch.object( + DataA2AServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DataA2AServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_data_a2a_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [DataA2AServiceClient, DataA2AServiceAsyncClient] +) +@mock.patch.object( + DataA2AServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DataA2AServiceClient), +) +@mock.patch.object( + DataA2AServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DataA2AServiceAsyncClient), +) +def test_data_a2a_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + 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 cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + 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 expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + 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 expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize( + "client_class", [DataA2AServiceClient, DataA2AServiceAsyncClient] +) +@mock.patch.object( + DataA2AServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DataA2AServiceClient), +) +@mock.patch.object( + DataA2AServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DataA2AServiceAsyncClient), +) +def test_data_a2a_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = DataA2AServiceClient._DEFAULT_UNIVERSE + default_endpoint = DataA2AServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = DataA2AServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (DataA2AServiceClient, transports.DataA2AServiceGrpcTransport, "grpc"), + ( + DataA2AServiceAsyncClient, + transports.DataA2AServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (DataA2AServiceClient, transports.DataA2AServiceRestTransport, "rest"), + ], +) +def test_data_a2a_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + DataA2AServiceClient, + transports.DataA2AServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + DataA2AServiceAsyncClient, + transports.DataA2AServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (DataA2AServiceClient, transports.DataA2AServiceRestTransport, "rest", None), + ], +) +def test_data_a2a_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_data_a2a_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.geminidataanalytics_v1beta.services.data_a2a_service.transports.DataA2AServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = DataA2AServiceClient( + 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", + [ + ( + DataA2AServiceClient, + transports.DataA2AServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + DataA2AServiceAsyncClient, + transports.DataA2AServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_data_a2a_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "geminidataanalytics.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="geminidataanalytics.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + data_a2a_service.SendMessageRequest(), + {}, + ], +) +def test_send_message(request_type, transport: str = "grpc"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = data_a2a_service.SendMessageResponse() + response = client.send_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = data_a2a_service.SendMessageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, data_a2a_service.SendMessageResponse) + + +def test_send_message_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = data_a2a_service.SendMessageRequest( + tenant="tenant_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.send_message(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.SendMessageRequest( + tenant="tenant_value", + ) + assert args[0] == request_msg + + +def test_send_message_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.send_message in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.send_message] = mock_rpc + request = {} + client.send_message(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.send_message(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_send_message_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.send_message + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.send_message + ] = mock_rpc + + request = {} + await client.send_message(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.send_message(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + data_a2a_service.SendMessageRequest(), + {}, + ], +) +async def test_send_message_async(request_type, transport: str = "grpc_asyncio"): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_a2a_service.SendMessageResponse() + ) + response = await client.send_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = data_a2a_service.SendMessageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, data_a2a_service.SendMessageResponse) + + +def test_send_message_field_headers(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_a2a_service.SendMessageRequest() + + request.tenant = "tenant_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + call.return_value = data_a2a_service.SendMessageResponse() + client.send_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "tenant=tenant_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_send_message_field_headers_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_a2a_service.SendMessageRequest() + + request.tenant = "tenant_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_a2a_service.SendMessageResponse() + ) + await client.send_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "tenant=tenant_value", + ) in kw["metadata"] + + +def test_send_message_flattened(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = data_a2a_service.SendMessageResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.send_message( + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_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].tenant + mock_val = "tenant_value" + assert arg == mock_val + arg = args[0].message + mock_val = data_a2a_service.A2AMessage(message_id="message_id_value") + assert arg == mock_val + + +def test_send_message_flattened_error(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.send_message( + data_a2a_service.SendMessageRequest(), + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_id_value"), + ) + + +@pytest.mark.asyncio +async def test_send_message_flattened_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = data_a2a_service.SendMessageResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_a2a_service.SendMessageResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.send_message( + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_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].tenant + mock_val = "tenant_value" + assert arg == mock_val + arg = args[0].message + mock_val = data_a2a_service.A2AMessage(message_id="message_id_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_send_message_flattened_error_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.send_message( + data_a2a_service.SendMessageRequest(), + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_id_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + data_a2a_service.SendMessageRequest(), + {}, + ], +) +def test_send_streaming_message(request_type, transport: str = "grpc"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iter([data_a2a_service.StreamResponse()]) + response = client.send_streaming_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = data_a2a_service.SendMessageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, data_a2a_service.StreamResponse) + + +def test_send_streaming_message_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = data_a2a_service.SendMessageRequest( + tenant="tenant_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.send_streaming_message(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.SendMessageRequest( + tenant="tenant_value", + ) + assert args[0] == request_msg + + +def test_send_streaming_message_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.send_streaming_message + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.send_streaming_message] = ( + mock_rpc + ) + request = {} + client.send_streaming_message(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.send_streaming_message(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_send_streaming_message_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.send_streaming_message + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.send_streaming_message + ] = mock_rpc + + request = {} + await client.send_streaming_message(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.send_streaming_message(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + data_a2a_service.SendMessageRequest(), + {}, + ], +) +async def test_send_streaming_message_async( + request_type, transport: str = "grpc_asyncio" +): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock( + side_effect=[data_a2a_service.StreamResponse()] + ) + response = await client.send_streaming_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = data_a2a_service.SendMessageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, data_a2a_service.StreamResponse) + + +def test_send_streaming_message_field_headers(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_a2a_service.SendMessageRequest() + + request.tenant = "tenant_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + call.return_value = iter([data_a2a_service.StreamResponse()]) + client.send_streaming_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "tenant=tenant_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_send_streaming_message_field_headers_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_a2a_service.SendMessageRequest() + + request.tenant = "tenant_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock( + side_effect=[data_a2a_service.StreamResponse()] + ) + await client.send_streaming_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "tenant=tenant_value", + ) in kw["metadata"] + + +def test_send_streaming_message_flattened(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iter([data_a2a_service.StreamResponse()]) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.send_streaming_message( + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_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].tenant + mock_val = "tenant_value" + assert arg == mock_val + arg = args[0].message + mock_val = data_a2a_service.A2AMessage(message_id="message_id_value") + assert arg == mock_val + + +def test_send_streaming_message_flattened_error(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.send_streaming_message( + data_a2a_service.SendMessageRequest(), + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_id_value"), + ) + + +@pytest.mark.asyncio +async def test_send_streaming_message_flattened_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iter([data_a2a_service.StreamResponse()]) + + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.send_streaming_message( + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_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].tenant + mock_val = "tenant_value" + assert arg == mock_val + arg = args[0].message + mock_val = data_a2a_service.A2AMessage(message_id="message_id_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_send_streaming_message_flattened_error_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.send_streaming_message( + data_a2a_service.SendMessageRequest(), + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_id_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + data_a2a_service.GetAgentCardRequest(), + {}, + ], +) +def test_get_agent_card(request_type, transport: str = "grpc"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_agent_card), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = data_a2a_service.AgentCard( + protocol_version="protocol_version_value", + name="name_value", + description="description_value", + url="url_value", + preferred_transport="preferred_transport_value", + version="version_value", + documentation_url="documentation_url_value", + default_input_modes=["default_input_modes_value"], + default_output_modes=["default_output_modes_value"], + supports_authenticated_extended_card=True, + icon_url="icon_url_value", + ) + response = client.get_agent_card(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = data_a2a_service.GetAgentCardRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, data_a2a_service.AgentCard) + assert response.protocol_version == "protocol_version_value" + assert response.name == "name_value" + assert response.description == "description_value" + assert response.url == "url_value" + assert response.preferred_transport == "preferred_transport_value" + assert response.version == "version_value" + assert response.documentation_url == "documentation_url_value" + assert response.default_input_modes == ["default_input_modes_value"] + assert response.default_output_modes == ["default_output_modes_value"] + assert response.supports_authenticated_extended_card is True + assert response.icon_url == "icon_url_value" + + +def test_get_agent_card_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = data_a2a_service.GetAgentCardRequest( + tenant="tenant_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_agent_card), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_agent_card(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.GetAgentCardRequest( + tenant="tenant_value", + ) + assert args[0] == request_msg + + +def test_get_agent_card_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_agent_card in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_agent_card] = mock_rpc + request = {} + client.get_agent_card(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_agent_card(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_agent_card_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_agent_card + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_agent_card + ] = mock_rpc + + request = {} + await client.get_agent_card(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_agent_card(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + data_a2a_service.GetAgentCardRequest(), + {}, + ], +) +async def test_get_agent_card_async(request_type, transport: str = "grpc_asyncio"): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_agent_card), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_a2a_service.AgentCard( + protocol_version="protocol_version_value", + name="name_value", + description="description_value", + url="url_value", + preferred_transport="preferred_transport_value", + version="version_value", + documentation_url="documentation_url_value", + default_input_modes=["default_input_modes_value"], + default_output_modes=["default_output_modes_value"], + supports_authenticated_extended_card=True, + icon_url="icon_url_value", + ) + ) + response = await client.get_agent_card(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = data_a2a_service.GetAgentCardRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, data_a2a_service.AgentCard) + assert response.protocol_version == "protocol_version_value" + assert response.name == "name_value" + assert response.description == "description_value" + assert response.url == "url_value" + assert response.preferred_transport == "preferred_transport_value" + assert response.version == "version_value" + assert response.documentation_url == "documentation_url_value" + assert response.default_input_modes == ["default_input_modes_value"] + assert response.default_output_modes == ["default_output_modes_value"] + assert response.supports_authenticated_extended_card is True + assert response.icon_url == "icon_url_value" + + +def test_get_agent_card_field_headers(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_a2a_service.GetAgentCardRequest() + + request.tenant = "tenant_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_agent_card), "__call__") as call: + call.return_value = data_a2a_service.AgentCard() + client.get_agent_card(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "tenant=tenant_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_agent_card_field_headers_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_a2a_service.GetAgentCardRequest() + + request.tenant = "tenant_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_agent_card), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_a2a_service.AgentCard() + ) + await client.get_agent_card(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "tenant=tenant_value", + ) in kw["metadata"] + + +def test_get_agent_card_flattened(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_agent_card), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = data_a2a_service.AgentCard() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_agent_card( + tenant="tenant_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].tenant + mock_val = "tenant_value" + assert arg == mock_val + + +def test_get_agent_card_flattened_error(): + client = DataA2AServiceClient( + credentials=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_agent_card( + data_a2a_service.GetAgentCardRequest(), + tenant="tenant_value", + ) + + +@pytest.mark.asyncio +async def test_get_agent_card_flattened_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_agent_card), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = data_a2a_service.AgentCard() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_a2a_service.AgentCard() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_agent_card( + tenant="tenant_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].tenant + mock_val = "tenant_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_agent_card_flattened_error_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_agent_card( + data_a2a_service.GetAgentCardRequest(), + tenant="tenant_value", + ) + + +def test_send_message_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.send_message in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.send_message] = mock_rpc + + request = {} + client.send_message(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.send_message(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_send_message_rest_required_fields( + request_type=data_a2a_service.SendMessageRequest, +): + transport_class = transports.DataA2AServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseSendMessage, + "_BaseSendMessage__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # verify required fields with non-default values are left alone + + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = data_a2a_service.SendMessageResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_a2a_service.SendMessageResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.send_message(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_send_message_rest_flattened(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = data_a2a_service.SendMessageResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"tenant": "projects/sample1/locations/sample2/agents/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_id_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = data_a2a_service.SendMessageResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.send_message(**mock_args) + + # Establish that the underlying call 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/a2a/{tenant=projects/*/locations/*/agents/*}/v1/message:send" + % client.transport._host, + args[1], + ) + + +def test_send_message_rest_flattened_error(transport: str = "rest"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.send_message( + data_a2a_service.SendMessageRequest(), + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_id_value"), + ) + + +def test_send_streaming_message_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.send_streaming_message + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.send_streaming_message] = ( + mock_rpc + ) + + request = {} + client.send_streaming_message(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.send_streaming_message(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_send_streaming_message_rest_required_fields( + request_type=data_a2a_service.SendMessageRequest, +): + transport_class = transports.DataA2AServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseSendStreamingMessage, + "_BaseSendStreamingMessage__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # verify required fields with non-default values are left alone + + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = data_a2a_service.StreamResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_a2a_service.StreamResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(json_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + with mock.patch.object(response_value, "iter_content") as iter_content: + iter_content.return_value = iter(json_return_value) + response = client.send_streaming_message(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_send_streaming_message_rest_flattened(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = data_a2a_service.StreamResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"tenant": "projects/sample1/locations/sample2/agents/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_id_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = data_a2a_service.StreamResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(json_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + with mock.patch.object(response_value, "iter_content") as iter_content: + iter_content.return_value = iter(json_return_value) + client.send_streaming_message(**mock_args) + + # Establish that the underlying call 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/a2a/{tenant=projects/*/locations/*/agents/*}/v1/message:stream" + % client.transport._host, + args[1], + ) + + +def test_send_streaming_message_rest_flattened_error(transport: str = "rest"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.send_streaming_message( + data_a2a_service.SendMessageRequest(), + tenant="tenant_value", + message=data_a2a_service.A2AMessage(message_id="message_id_value"), + ) + + +def test_get_agent_card_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_agent_card in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_agent_card] = mock_rpc + + request = {} + client.get_agent_card(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_agent_card(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_agent_card_rest_flattened(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = data_a2a_service.AgentCard() + + # get arguments that satisfy an http rule for this method + sample_request = {"tenant": "projects/sample1/locations/sample2/agents/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + tenant="tenant_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = data_a2a_service.AgentCard.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_agent_card(**mock_args) + + # Establish that the underlying call 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/a2a/{tenant=projects/*/locations/*/agents/*}/v1/card" + % client.transport._host, + args[1], + ) + + +def test_get_agent_card_rest_flattened_error(transport: str = "rest"): + client = DataA2AServiceClient( + credentials=ga_credentials.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_agent_card( + data_a2a_service.GetAgentCardRequest(), + tenant="tenant_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DataA2AServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DataA2AServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataA2AServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DataA2AServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DataA2AServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DataA2AServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DataA2AServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataA2AServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataA2AServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DataA2AServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataA2AServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DataA2AServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DataA2AServiceGrpcTransport, + transports.DataA2AServiceGrpcAsyncIOTransport, + transports.DataA2AServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = DataA2AServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_send_message_empty_call_grpc(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + call.return_value = data_a2a_service.SendMessageResponse() + client.send_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.SendMessageRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_send_streaming_message_empty_call_grpc(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + call.return_value = iter([data_a2a_service.StreamResponse()]) + client.send_streaming_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.SendMessageRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_agent_card_empty_call_grpc(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_agent_card), "__call__") as call: + call.return_value = data_a2a_service.AgentCard() + client.get_agent_card(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.GetAgentCardRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = DataA2AServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_send_message_empty_call_grpc_asyncio(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_a2a_service.SendMessageResponse() + ) + await client.send_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.SendMessageRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_send_streaming_message_empty_call_grpc_asyncio(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock( + side_effect=[data_a2a_service.StreamResponse()] + ) + await client.send_streaming_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.SendMessageRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_agent_card_empty_call_grpc_asyncio(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_agent_card), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_a2a_service.AgentCard( + protocol_version="protocol_version_value", + name="name_value", + description="description_value", + url="url_value", + preferred_transport="preferred_transport_value", + version="version_value", + documentation_url="documentation_url_value", + default_input_modes=["default_input_modes_value"], + default_output_modes=["default_output_modes_value"], + supports_authenticated_extended_card=True, + icon_url="icon_url_value", + ) + ) + await client.get_agent_card(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.GetAgentCardRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = DataA2AServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_send_message_rest_bad_request( + request_type=data_a2a_service.SendMessageRequest, +): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"tenant": "projects/sample1/locations/sample2/agents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.send_message(request) + + +@pytest.mark.parametrize( + "request_type", + [ + data_a2a_service.SendMessageRequest, + dict, + ], +) +def test_send_message_rest_call_success(request_type): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"tenant": "projects/sample1/locations/sample2/agents/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 = data_a2a_service.SendMessageResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_a2a_service.SendMessageResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.send_message(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, data_a2a_service.SendMessageResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_send_message_rest_interceptors(null_interceptor): + transport = transports.DataA2AServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DataA2AServiceRestInterceptor(), + ) + client = DataA2AServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DataA2AServiceRestInterceptor, "post_send_message" + ) as post, + mock.patch.object( + transports.DataA2AServiceRestInterceptor, "post_send_message_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.DataA2AServiceRestInterceptor, "pre_send_message" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = data_a2a_service.SendMessageRequest.pb( + data_a2a_service.SendMessageRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = data_a2a_service.SendMessageResponse.to_json( + data_a2a_service.SendMessageResponse() + ) + req.return_value.content = return_value + + request = data_a2a_service.SendMessageRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = data_a2a_service.SendMessageResponse() + post_with_metadata.return_value = ( + data_a2a_service.SendMessageResponse(), + metadata, + ) + + client.send_message( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_send_streaming_message_rest_bad_request( + request_type=data_a2a_service.SendMessageRequest, +): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"tenant": "projects/sample1/locations/sample2/agents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.send_streaming_message(request) + + +@pytest.mark.parametrize( + "request_type", + [ + data_a2a_service.SendMessageRequest, + dict, + ], +) +def test_send_streaming_message_rest_call_success(request_type): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"tenant": "projects/sample1/locations/sample2/agents/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 = data_a2a_service.StreamResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_a2a_service.StreamResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(json_return_value) + response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.send_streaming_message(request) + + assert isinstance(response, Iterable) + response = next(response) + + # Establish that the response is the type that we expect. + assert isinstance(response, data_a2a_service.StreamResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_send_streaming_message_rest_interceptors(null_interceptor): + transport = transports.DataA2AServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DataA2AServiceRestInterceptor(), + ) + client = DataA2AServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DataA2AServiceRestInterceptor, "post_send_streaming_message" + ) as post, + mock.patch.object( + transports.DataA2AServiceRestInterceptor, + "post_send_streaming_message_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DataA2AServiceRestInterceptor, "pre_send_streaming_message" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = data_a2a_service.SendMessageRequest.pb( + data_a2a_service.SendMessageRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = data_a2a_service.StreamResponse.to_json( + data_a2a_service.StreamResponse() + ) + req.return_value.iter_content = mock.Mock(return_value=iter(return_value)) + + request = data_a2a_service.SendMessageRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = data_a2a_service.StreamResponse() + post_with_metadata.return_value = data_a2a_service.StreamResponse(), metadata + + client.send_streaming_message( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_agent_card_rest_bad_request( + request_type=data_a2a_service.GetAgentCardRequest, +): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"tenant": "projects/sample1/locations/sample2/agents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_agent_card(request) + + +@pytest.mark.parametrize( + "request_type", + [ + data_a2a_service.GetAgentCardRequest, + dict, + ], +) +def test_get_agent_card_rest_call_success(request_type): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"tenant": "projects/sample1/locations/sample2/agents/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 = data_a2a_service.AgentCard( + protocol_version="protocol_version_value", + name="name_value", + description="description_value", + url="url_value", + preferred_transport="preferred_transport_value", + version="version_value", + documentation_url="documentation_url_value", + default_input_modes=["default_input_modes_value"], + default_output_modes=["default_output_modes_value"], + supports_authenticated_extended_card=True, + icon_url="icon_url_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_a2a_service.AgentCard.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_agent_card(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, data_a2a_service.AgentCard) + assert response.protocol_version == "protocol_version_value" + assert response.name == "name_value" + assert response.description == "description_value" + assert response.url == "url_value" + assert response.preferred_transport == "preferred_transport_value" + assert response.version == "version_value" + assert response.documentation_url == "documentation_url_value" + assert response.default_input_modes == ["default_input_modes_value"] + assert response.default_output_modes == ["default_output_modes_value"] + assert response.supports_authenticated_extended_card is True + assert response.icon_url == "icon_url_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_agent_card_rest_interceptors(null_interceptor): + transport = transports.DataA2AServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DataA2AServiceRestInterceptor(), + ) + client = DataA2AServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DataA2AServiceRestInterceptor, "post_get_agent_card" + ) as post, + mock.patch.object( + transports.DataA2AServiceRestInterceptor, + "post_get_agent_card_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DataA2AServiceRestInterceptor, "pre_get_agent_card" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = data_a2a_service.GetAgentCardRequest.pb( + data_a2a_service.GetAgentCardRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = data_a2a_service.AgentCard.to_json(data_a2a_service.AgentCard()) + req.return_value.content = return_value + + request = data_a2a_service.GetAgentCardRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = data_a2a_service.AgentCard() + post_with_metadata.return_value = data_a2a_service.AgentCard(), metadata + + client.get_agent_card( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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( + request_type=operations_pb2.DeleteOperationRequest, +): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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( + request_type=operations_pb2.GetOperationRequest, +): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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( + request_type=operations_pb2.ListOperationsRequest, +): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_send_message_empty_call_rest(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.send_message), "__call__") as call: + client.send_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.SendMessageRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_send_streaming_message_empty_call_rest(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.send_streaming_message), "__call__" + ) as call: + client.send_streaming_message(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.SendMessageRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_agent_card_empty_call_rest(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_agent_card), "__call__") as call: + client.get_agent_card(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_a2a_service.GetAgentCardRequest() + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DataA2AServiceGrpcTransport, + ) + + +def test_data_a2a_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DataA2AServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_data_a2a_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.geminidataanalytics_v1beta.services.data_a2a_service.transports.DataA2AServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.DataA2AServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "send_message", + "send_streaming_message", + "get_agent_card", + "get_location", + "list_locations", + "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() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_data_a2a_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.cloud.geminidataanalytics_v1beta.services.data_a2a_service.transports.DataA2AServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataA2AServiceTransport( + 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_data_a2a_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.cloud.geminidataanalytics_v1beta.services.data_a2a_service.transports.DataA2AServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataA2AServiceTransport() + adc.assert_called_once() + + +def test_data_a2a_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DataA2AServiceClient() + 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.DataA2AServiceGrpcTransport, + transports.DataA2AServiceGrpcAsyncIOTransport, + ], +) +def test_data_a2a_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DataA2AServiceGrpcTransport, + transports.DataA2AServiceGrpcAsyncIOTransport, + transports.DataA2AServiceRestTransport, + ], +) +def test_data_a2a_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DataA2AServiceGrpcTransport, grpc_helpers), + (transports.DataA2AServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_data_a2a_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "geminidataanalytics.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="geminidataanalytics.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DataA2AServiceGrpcTransport, + transports.DataA2AServiceGrpcAsyncIOTransport, + ], +) +def test_data_a2a_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_data_a2a_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.DataA2AServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_data_a2a_service_host_no_port(transport_name): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="geminidataanalytics.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "geminidataanalytics.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://geminidataanalytics.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_data_a2a_service_host_with_port(transport_name): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="geminidataanalytics.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "geminidataanalytics.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://geminidataanalytics.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_data_a2a_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DataA2AServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DataA2AServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.send_message._session + session2 = client2.transport.send_message._session + assert session1 != session2 + session1 = client1.transport.send_streaming_message._session + session2 = client2.transport.send_streaming_message._session + assert session1 != session2 + session1 = client1.transport.get_agent_card._session + session2 = client2.transport.get_agent_card._session + assert session1 != session2 + + +def test_data_a2a_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataA2AServiceGrpcTransport( + 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_data_a2a_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataA2AServiceGrpcAsyncIOTransport( + 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.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [ + transports.DataA2AServiceGrpcTransport, + transports.DataA2AServiceGrpcAsyncIOTransport, + ], +) +def test_data_a2a_service_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.DataA2AServiceGrpcTransport, + transports.DataA2AServiceGrpcAsyncIOTransport, + ], +) +def test_data_a2a_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = DataA2AServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = DataA2AServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DataA2AServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = DataA2AServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = DataA2AServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DataA2AServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = DataA2AServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = DataA2AServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DataA2AServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = DataA2AServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = DataA2AServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DataA2AServiceClient.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 = DataA2AServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = DataA2AServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DataA2AServiceClient.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.DataA2AServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.DataA2AServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = DataA2AServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.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 = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.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 = DataA2AServiceClient( + 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 = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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_delete_operation_flattened(): + client = DataA2AServiceClient( + 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 + + client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +@pytest.mark.asyncio +async def test_delete_operation_flattened_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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) + await client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +def test_cancel_operation(transport: str = "grpc"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_asyncio"): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.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 = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.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 = DataA2AServiceClient( + 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 = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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_cancel_operation_flattened(): + client = DataA2AServiceClient( + 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 + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +def test_get_operation(transport: str = "grpc"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = DataA2AServiceClient( + 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 = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation_flattened(): + client = DataA2AServiceClient( + 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() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +def test_list_operations(transport: str = "grpc"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.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 = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.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 = DataA2AServiceClient( + 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 = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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_list_operations_flattened(): + client = DataA2AServiceClient( + 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() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +def test_list_locations(transport: str = "grpc"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_locations_from_dict(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations_flattened(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +@pytest.mark.asyncio +async def test_list_locations_flattened_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +def test_get_location(transport: str = "grpc"): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_get_location_field_headers(): + client = DataA2AServiceClient(credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = DataA2AServiceAsyncClient(credentials=async_anonymous_credentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +def test_get_location_from_dict(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location_flattened(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +@pytest.mark.asyncio +async def test_get_location_flattened_async(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +def test_transport_close_grpc(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = DataA2AServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = DataA2AServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = DataA2AServiceClient( + 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", + [ + (DataA2AServiceClient, transports.DataA2AServiceGrpcTransport), + (DataA2AServiceAsyncClient, transports.DataA2AServiceGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_agent_service.py b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_agent_service.py index 743536901490..d53ad1ddf8e5 100644 --- a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_agent_service.py +++ b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_agent_service.py @@ -2224,6 +2224,7 @@ def test_get_data_agent(request_type, transport: str = "grpc"): display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) response = client.get_data_agent(request) @@ -2239,6 +2240,7 @@ def test_get_data_agent(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" assert response.description == "description_value" assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True def test_get_data_agent_non_empty_request_with_auto_populated_field(): @@ -2374,6 +2376,7 @@ async def test_get_data_agent_async(request_type, transport: str = "grpc_asyncio display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) ) response = await client.get_data_agent(request) @@ -2390,6 +2393,7 @@ async def test_get_data_agent_async(request_type, transport: str = "grpc_asyncio assert response.display_name == "display_name_value" assert response.description == "description_value" assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True def test_get_data_agent_field_headers(): @@ -2964,6 +2968,7 @@ def test_create_data_agent_sync(request_type, transport: str = "grpc"): display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) response = client.create_data_agent_sync(request) @@ -2979,6 +2984,7 @@ def test_create_data_agent_sync(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" assert response.description == "description_value" assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True def test_create_data_agent_sync_non_empty_request_with_auto_populated_field(): @@ -3127,6 +3133,7 @@ async def test_create_data_agent_sync_async( display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) ) response = await client.create_data_agent_sync(request) @@ -3143,6 +3150,7 @@ async def test_create_data_agent_sync_async( assert response.display_name == "display_name_value" assert response.description == "description_value" assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True def test_create_data_agent_sync_field_headers(): @@ -3765,6 +3773,7 @@ def test_update_data_agent_sync(request_type, transport: str = "grpc"): display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) response = client.update_data_agent_sync(request) @@ -3780,6 +3789,7 @@ def test_update_data_agent_sync(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" assert response.description == "description_value" assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True def test_update_data_agent_sync_non_empty_request_with_auto_populated_field(): @@ -3922,6 +3932,7 @@ async def test_update_data_agent_sync_async( display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) ) response = await client.update_data_agent_sync(request) @@ -3938,6 +3949,7 @@ async def test_update_data_agent_sync_async( assert response.display_name == "display_name_value" assert response.description == "description_value" assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True def test_update_data_agent_sync_field_headers(): @@ -5497,6 +5509,758 @@ async def test_set_iam_policy_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + data_agent_service.SetAgentOpsObservabilityRequest(), + {}, + ], +) +def test_set_agent_ops_observability(request_type, transport: str = "grpc"): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.set_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = data_agent_service.SetAgentOpsObservabilityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_set_agent_ops_observability_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = data_agent_service.SetAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.set_agent_ops_observability(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.SetAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + assert args[0] == request_msg + + +def test_set_agent_ops_observability_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.set_agent_ops_observability + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.set_agent_ops_observability + ] = mock_rpc + request = {} + client.set_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.set_agent_ops_observability(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_set_agent_ops_observability_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.set_agent_ops_observability + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.set_agent_ops_observability + ] = mock_rpc + + request = {} + await client.set_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.set_agent_ops_observability(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + data_agent_service.SetAgentOpsObservabilityRequest(), + {}, + ], +) +async def test_set_agent_ops_observability_async( + request_type, transport: str = "grpc_asyncio" +): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__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.set_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = data_agent_service.SetAgentOpsObservabilityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_set_agent_ops_observability_field_headers(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_agent_service.SetAgentOpsObservabilityRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.set_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_set_agent_ops_observability_field_headers_async(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_agent_service.SetAgentOpsObservabilityRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.set_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_set_agent_ops_observability_flattened(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__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.set_agent_ops_observability( + parent="parent_value", + telemetry_enabled=True, + data_source_type="data_source_type_value", + ) + + # Establish that the 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].telemetry_enabled + mock_val = True + assert arg == mock_val + arg = args[0].data_source_type + mock_val = "data_source_type_value" + assert arg == mock_val + + +def test_set_agent_ops_observability_flattened_error(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_agent_ops_observability( + data_agent_service.SetAgentOpsObservabilityRequest(), + parent="parent_value", + telemetry_enabled=True, + data_source_type="data_source_type_value", + ) + + +@pytest.mark.asyncio +async def test_set_agent_ops_observability_flattened_async(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__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.set_agent_ops_observability( + parent="parent_value", + telemetry_enabled=True, + data_source_type="data_source_type_value", + ) + + # Establish that 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].telemetry_enabled + mock_val = True + assert arg == mock_val + arg = args[0].data_source_type + mock_val = "data_source_type_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_set_agent_ops_observability_flattened_error_async(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_agent_ops_observability( + data_agent_service.SetAgentOpsObservabilityRequest(), + parent="parent_value", + telemetry_enabled=True, + data_source_type="data_source_type_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + data_agent_service.RetrieveAgentOpsObservabilityRequest(), + {}, + ], +) +def test_retrieve_agent_ops_observability(request_type, transport: str = "grpc"): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse( + telemetry_enabled=True, + bigquery_enabled=True, + cloud_trace_enabled=True, + cloud_monitoring_enabled=True, + cloud_logging_enabled=True, + bqaa_enabled=True, + ) + response = client.retrieve_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = data_agent_service.RetrieveAgentOpsObservabilityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, data_agent_service.RetrieveAgentOpsObservabilityResponse + ) + assert response.telemetry_enabled is True + assert response.bigquery_enabled is True + assert response.cloud_trace_enabled is True + assert response.cloud_monitoring_enabled is True + assert response.cloud_logging_enabled is True + assert response.bqaa_enabled is True + + +def test_retrieve_agent_ops_observability_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = data_agent_service.RetrieveAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.retrieve_agent_ops_observability(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.RetrieveAgentOpsObservabilityRequest( + parent="parent_value", + data_source_type="data_source_type_value", + ) + assert args[0] == request_msg + + +def test_retrieve_agent_ops_observability_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.retrieve_agent_ops_observability + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.retrieve_agent_ops_observability + ] = mock_rpc + request = {} + client.retrieve_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.retrieve_agent_ops_observability(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_retrieve_agent_ops_observability_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.retrieve_agent_ops_observability + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.retrieve_agent_ops_observability + ] = mock_rpc + + request = {} + await client.retrieve_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.retrieve_agent_ops_observability(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + data_agent_service.RetrieveAgentOpsObservabilityRequest(), + {}, + ], +) +async def test_retrieve_agent_ops_observability_async( + request_type, transport: str = "grpc_asyncio" +): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_agent_service.RetrieveAgentOpsObservabilityResponse( + telemetry_enabled=True, + bigquery_enabled=True, + cloud_trace_enabled=True, + cloud_monitoring_enabled=True, + cloud_logging_enabled=True, + bqaa_enabled=True, + ) + ) + response = await client.retrieve_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = data_agent_service.RetrieveAgentOpsObservabilityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, data_agent_service.RetrieveAgentOpsObservabilityResponse + ) + assert response.telemetry_enabled is True + assert response.bigquery_enabled is True + assert response.cloud_trace_enabled is True + assert response.cloud_monitoring_enabled is True + assert response.cloud_logging_enabled is True + assert response.bqaa_enabled is True + + +def test_retrieve_agent_ops_observability_field_headers(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_agent_service.RetrieveAgentOpsObservabilityRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + call.return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() + client.retrieve_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_retrieve_agent_ops_observability_field_headers_async(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = data_agent_service.RetrieveAgentOpsObservabilityRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_agent_service.RetrieveAgentOpsObservabilityResponse() + ) + await client.retrieve_agent_ops_observability(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_retrieve_agent_ops_observability_flattened(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.retrieve_agent_ops_observability( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Establish that the 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].data_source_type + mock_val = "data_source_type_value" + assert arg == mock_val + + +def test_retrieve_agent_ops_observability_flattened_error(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.retrieve_agent_ops_observability( + data_agent_service.RetrieveAgentOpsObservabilityRequest(), + parent="parent_value", + data_source_type="data_source_type_value", + ) + + +@pytest.mark.asyncio +async def test_retrieve_agent_ops_observability_flattened_async(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_agent_service.RetrieveAgentOpsObservabilityResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.retrieve_agent_ops_observability( + parent="parent_value", + data_source_type="data_source_type_value", + ) + + # Establish that 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].data_source_type + mock_val = "data_source_type_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_retrieve_agent_ops_observability_flattened_error_async(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.retrieve_agent_ops_observability( + data_agent_service.RetrieveAgentOpsObservabilityRequest(), + parent="parent_value", + data_source_type="data_source_type_value", + ) + + def test_list_data_agents_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5511,37 +6275,541 @@ def test_list_data_agents_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_data_agents in client._transport._wrapped_methods + assert client._transport.list_data_agents in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_data_agents] = ( + mock_rpc + ) + + request = {} + client.list_data_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_agents(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_data_agents_rest_required_fields( + request_type=data_agent_service.ListDataAgentsRequest, +): + transport_class = transports.DataAgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListDataAgents, + "_BaseListDataAgents__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "creatorFilter", + "filter", + "orderBy", + "pageSize", + "pageToken", + "showDeleted", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = data_agent_service.ListDataAgentsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_agent_service.ListDataAgentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_data_agents(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_data_agents_rest_flattened(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = data_agent_service.ListDataAgentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = data_agent_service.ListDataAgentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_data_agents(**mock_args) + + # Establish that the underlying call 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/*}/dataAgents" + % client.transport._host, + args[1], + ) + + +def test_list_data_agents_rest_flattened_error(transport: str = "rest"): + client = DataAgentServiceClient( + credentials=ga_credentials.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_data_agents( + data_agent_service.ListDataAgentsRequest(), + parent="parent_value", + ) + + +def test_list_data_agents_rest_pager(transport: str = "rest"): + client = DataAgentServiceClient( + 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 = ( + data_agent_service.ListDataAgentsResponse( + data_agents=[ + data_agent.DataAgent(), + data_agent.DataAgent(), + data_agent.DataAgent(), + ], + next_page_token="abc", + ), + data_agent_service.ListDataAgentsResponse( + data_agents=[], + next_page_token="def", + ), + data_agent_service.ListDataAgentsResponse( + data_agents=[ + data_agent.DataAgent(), + ], + next_page_token="ghi", + ), + data_agent_service.ListDataAgentsResponse( + data_agents=[ + data_agent.DataAgent(), + data_agent.DataAgent(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + data_agent_service.ListDataAgentsResponse.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_data_agents(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, data_agent.DataAgent) for i in results) + + pages = list(client.list_data_agents(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_accessible_data_agents_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_accessible_data_agents + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_accessible_data_agents + ] = mock_rpc + + request = {} + client.list_accessible_data_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_accessible_data_agents(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_accessible_data_agents_rest_required_fields( + request_type=data_agent_service.ListAccessibleDataAgentsRequest, +): + transport_class = transports.DataAgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListAccessibleDataAgents, + "_BaseListAccessibleDataAgents__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "creatorFilter", + "filter", + "orderBy", + "pageSize", + "pageToken", + "showDeleted", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = data_agent_service.ListAccessibleDataAgentsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_agent_service.ListAccessibleDataAgentsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_accessible_data_agents(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_accessible_data_agents_rest_flattened(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = data_agent_service.ListAccessibleDataAgentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = data_agent_service.ListAccessibleDataAgentsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_accessible_data_agents(**mock_args) + + # Establish that the underlying call 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/*}/dataAgents:listAccessible" + % client.transport._host, + args[1], + ) + + +def test_list_accessible_data_agents_rest_flattened_error(transport: str = "rest"): + client = DataAgentServiceClient( + credentials=ga_credentials.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_accessible_data_agents( + data_agent_service.ListAccessibleDataAgentsRequest(), + parent="parent_value", + ) + + +def test_list_accessible_data_agents_rest_pager(transport: str = "rest"): + client = DataAgentServiceClient( + 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 = ( + data_agent_service.ListAccessibleDataAgentsResponse( + data_agents=[ + data_agent.DataAgent(), + data_agent.DataAgent(), + data_agent.DataAgent(), + ], + next_page_token="abc", + ), + data_agent_service.ListAccessibleDataAgentsResponse( + data_agents=[], + next_page_token="def", + ), + data_agent_service.ListAccessibleDataAgentsResponse( + data_agents=[ + data_agent.DataAgent(), + ], + next_page_token="ghi", + ), + data_agent_service.ListAccessibleDataAgentsResponse( + data_agents=[ + data_agent.DataAgent(), + data_agent.DataAgent(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + data_agent_service.ListAccessibleDataAgentsResponse.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_accessible_data_agents(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, data_agent.DataAgent) for i in results) + + pages = list(client.list_accessible_data_agents(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_data_agent_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_agent in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_data_agents] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_data_agent] = mock_rpc request = {} - client.list_data_agents(request) + client.get_data_agent(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_data_agents(request) + client.get_data_agent(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_data_agents_rest_required_fields( - request_type=data_agent_service.ListDataAgentsRequest, +def test_get_data_agent_rest_required_fields( + request_type=data_agent_service.GetDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -5551,8 +6819,8 @@ def test_list_data_agents_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListDataAgents, - "_BaseListDataAgents__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetDataAgent, + "_BaseGetDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -5562,22 +6830,11 @@ def test_list_data_agents_rest_required_fields( # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - "showDeleted", - ) - ) + jsonified_request["name"] = "name_value" # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5586,7 +6843,7 @@ def test_list_data_agents_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = data_agent_service.ListDataAgentsResponse() + return_value = data_agent.DataAgent() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -5607,21 +6864,21 @@ def test_list_data_agents_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = data_agent_service.ListDataAgentsResponse.pb(return_value) + return_value = data_agent.DataAgent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_data_agents(request) + response = client.get_data_agent(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_data_agents_rest_flattened(): +def test_get_data_agent_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5630,14 +6887,16 @@ def test_list_data_agents_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = data_agent_service.ListDataAgentsResponse() + return_value = data_agent.DataAgent() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "name": "projects/sample1/locations/sample2/dataAgents/sample3" + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) @@ -5645,26 +6904,26 @@ def test_list_data_agents_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = data_agent_service.ListDataAgentsResponse.pb(return_value) + return_value = data_agent.DataAgent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_data_agents(**mock_args) + client.get_data_agent(**mock_args) # Establish that the underlying call 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/*}/dataAgents" + "%s/v1beta/{name=projects/*/locations/*/dataAgents/*}" % client.transport._host, args[1], ) -def test_list_data_agents_rest_flattened_error(transport: str = "rest"): +def test_get_data_agent_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5673,79 +6932,13 @@ def test_list_data_agents_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_data_agents( - data_agent_service.ListDataAgentsRequest(), - parent="parent_value", - ) - - -def test_list_data_agents_rest_pager(transport: str = "rest"): - client = DataAgentServiceClient( - 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 = ( - data_agent_service.ListDataAgentsResponse( - data_agents=[ - data_agent.DataAgent(), - data_agent.DataAgent(), - data_agent.DataAgent(), - ], - next_page_token="abc", - ), - data_agent_service.ListDataAgentsResponse( - data_agents=[], - next_page_token="def", - ), - data_agent_service.ListDataAgentsResponse( - data_agents=[ - data_agent.DataAgent(), - ], - next_page_token="ghi", - ), - data_agent_service.ListDataAgentsResponse( - data_agents=[ - data_agent.DataAgent(), - data_agent.DataAgent(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - data_agent_service.ListDataAgentsResponse.to_json(x) for x in response + client.get_data_agent( + data_agent_service.GetDataAgentRequest(), + name="name_value", ) - 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_data_agents(request=sample_request) - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, data_agent.DataAgent) for i in results) - - pages = list(client.list_data_agents(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token -def test_list_accessible_data_agents_rest_use_cached_wrapped_rpc(): +def test_create_data_agent_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5759,35 +6952,36 @@ def test_list_accessible_data_agents_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_accessible_data_agents - in client._transport._wrapped_methods - ) + assert client._transport.create_data_agent in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.list_accessible_data_agents - ] = mock_rpc + client._transport._wrapped_methods[client._transport.create_data_agent] = ( + mock_rpc + ) request = {} - client.list_accessible_data_agents(request) + client.create_data_agent(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_accessible_data_agents(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_data_agent(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_accessible_data_agents_rest_required_fields( - request_type=data_agent_service.ListAccessibleDataAgentsRequest, +def test_create_data_agent_rest_required_fields( + request_type=data_agent_service.CreateDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport @@ -5802,8 +6996,8 @@ def test_list_accessible_data_agents_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListAccessibleDataAgents, - "_BaseListAccessibleDataAgents__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseCreateDataAgent, + "_BaseCreateDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -5818,12 +7012,8 @@ def test_list_accessible_data_agents_rest_required_fields( # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "creatorFilter", - "filter", - "orderBy", - "pageSize", - "pageToken", - "showDeleted", + "dataAgentId", + "requestId", ) ) @@ -5838,7 +7028,7 @@ def test_list_accessible_data_agents_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = data_agent_service.ListAccessibleDataAgentsResponse() + 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 @@ -5850,32 +7040,28 @@ def test_list_accessible_data_agents_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = data_agent_service.ListAccessibleDataAgentsResponse.pb( - return_value - ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_accessible_data_agents(request) + response = client.create_data_agent(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_accessible_data_agents_rest_flattened(): +def test_create_data_agent_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5884,7 +7070,7 @@ def test_list_accessible_data_agents_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = data_agent_service.ListAccessibleDataAgentsResponse() + 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"} @@ -5892,35 +7078,39 @@ def test_list_accessible_data_agents_rest_flattened(): # get truthy value for each flattened field mock_args = dict( parent="parent_value", + data_agent=gcg_data_agent.DataAgent( + data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( + staging_context=context.Context( + system_instruction="system_instruction_value" + ) + ) + ), + data_agent_id="data_agent_id_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = data_agent_service.ListAccessibleDataAgentsResponse.pb( - return_value - ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_accessible_data_agents(**mock_args) + client.create_data_agent(**mock_args) # Establish that the underlying call 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/*}/dataAgents:listAccessible" + "%s/v1beta/{parent=projects/*/locations/*}/dataAgents" % client.transport._host, args[1], ) -def test_list_accessible_data_agents_rest_flattened_error(transport: str = "rest"): +def test_create_data_agent_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5929,80 +7119,21 @@ def test_list_accessible_data_agents_rest_flattened_error(transport: str = "rest # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_accessible_data_agents( - data_agent_service.ListAccessibleDataAgentsRequest(), + client.create_data_agent( + data_agent_service.CreateDataAgentRequest(), parent="parent_value", - ) - - -def test_list_accessible_data_agents_rest_pager(transport: str = "rest"): - client = DataAgentServiceClient( - 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 = ( - data_agent_service.ListAccessibleDataAgentsResponse( - data_agents=[ - data_agent.DataAgent(), - data_agent.DataAgent(), - data_agent.DataAgent(), - ], - next_page_token="abc", - ), - data_agent_service.ListAccessibleDataAgentsResponse( - data_agents=[], - next_page_token="def", - ), - data_agent_service.ListAccessibleDataAgentsResponse( - data_agents=[ - data_agent.DataAgent(), - ], - next_page_token="ghi", - ), - data_agent_service.ListAccessibleDataAgentsResponse( - data_agents=[ - data_agent.DataAgent(), - data_agent.DataAgent(), - ], + data_agent=gcg_data_agent.DataAgent( + data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( + staging_context=context.Context( + system_instruction="system_instruction_value" + ) + ) ), + data_agent_id="data_agent_id_value", ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - data_agent_service.ListAccessibleDataAgentsResponse.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_accessible_data_agents(request=sample_request) - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, data_agent.DataAgent) for i in results) - - pages = list(client.list_accessible_data_agents(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token -def test_get_data_agent_rest_use_cached_wrapped_rpc(): +def test_create_data_agent_sync_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6016,35 +7147,40 @@ def test_get_data_agent_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_data_agent in client._transport._wrapped_methods + assert ( + client._transport.create_data_agent_sync + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_data_agent] = mock_rpc + client._transport._wrapped_methods[client._transport.create_data_agent_sync] = ( + mock_rpc + ) request = {} - client.get_data_agent(request) + client.create_data_agent_sync(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_data_agent(request) + client.create_data_agent_sync(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_data_agent_rest_required_fields( - request_type=data_agent_service.GetDataAgentRequest, +def test_create_data_agent_sync_rest_required_fields( + request_type=data_agent_service.CreateDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6054,8 +7190,8 @@ def test_get_data_agent_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetDataAgent, - "_BaseGetDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseCreateDataAgentSync, + "_BaseCreateDataAgentSync__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6065,11 +7201,19 @@ def test_get_data_agent_rest_required_fields( # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "dataAgentId", + "requestId", + ) + ) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6078,7 +7222,7 @@ def test_get_data_agent_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = data_agent.DataAgent() + return_value = gcg_data_agent.DataAgent() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -6090,30 +7234,31 @@ def test_get_data_agent_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = data_agent.DataAgent.pb(return_value) + return_value = gcg_data_agent.DataAgent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_data_agent(request) + response = client.create_data_agent_sync(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_data_agent_rest_flattened(): +def test_create_data_agent_sync_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6122,16 +7267,22 @@ def test_get_data_agent_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = data_agent.DataAgent() + return_value = gcg_data_agent.DataAgent() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/dataAgents/sample3" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + data_agent=gcg_data_agent.DataAgent( + data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( + staging_context=context.Context( + system_instruction="system_instruction_value" + ) + ) + ), + data_agent_id="data_agent_id_value", ) mock_args.update(sample_request) @@ -6139,26 +7290,26 @@ def test_get_data_agent_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = data_agent.DataAgent.pb(return_value) + return_value = gcg_data_agent.DataAgent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_data_agent(**mock_args) + client.create_data_agent_sync(**mock_args) # Establish that the underlying call 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/*/dataAgents/*}" + "%s/v1beta/{parent=projects/*/locations/*}/dataAgents:createSync" % client.transport._host, args[1], ) -def test_get_data_agent_rest_flattened_error(transport: str = "rest"): +def test_create_data_agent_sync_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6167,13 +7318,21 @@ def test_get_data_agent_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_data_agent( - data_agent_service.GetDataAgentRequest(), - name="name_value", + client.create_data_agent_sync( + data_agent_service.CreateDataAgentRequest(), + parent="parent_value", + data_agent=gcg_data_agent.DataAgent( + data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( + staging_context=context.Context( + system_instruction="system_instruction_value" + ) + ) + ), + data_agent_id="data_agent_id_value", ) -def test_create_data_agent_rest_use_cached_wrapped_rpc(): +def test_update_data_agent_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6187,19 +7346,19 @@ def test_create_data_agent_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_data_agent in client._transport._wrapped_methods + assert client._transport.update_data_agent in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_data_agent] = ( + client._transport._wrapped_methods[client._transport.update_data_agent] = ( mock_rpc ) request = {} - client.create_data_agent(request) + client.update_data_agent(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6208,20 +7367,19 @@ def test_create_data_agent_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_data_agent(request) + client.update_data_agent(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_data_agent_rest_required_fields( - request_type=data_agent_service.CreateDataAgentRequest, +def test_update_data_agent_rest_required_fields( + request_type=data_agent_service.UpdateDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6231,8 +7389,8 @@ def test_create_data_agent_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseCreateDataAgent, - "_BaseCreateDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseUpdateDataAgent, + "_BaseUpdateDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6242,19 +7400,15 @@ def test_create_data_agent_rest_required_fields( # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "dataAgentId", "requestId", + "updateMask", ) ) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6275,7 +7429,7 @@ def test_create_data_agent_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -6289,14 +7443,14 @@ def test_create_data_agent_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_data_agent(request) + response = client.update_data_agent(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_data_agent_rest_flattened(): +def test_update_data_agent_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6308,11 +7462,14 @@ def test_create_data_agent_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "data_agent": { + "name": "projects/sample1/locations/sample2/dataAgents/sample3" + } + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", data_agent=gcg_data_agent.DataAgent( data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( staging_context=context.Context( @@ -6320,7 +7477,7 @@ def test_create_data_agent_rest_flattened(): ) ) ), - data_agent_id="data_agent_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -6332,20 +7489,20 @@ def test_create_data_agent_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_data_agent(**mock_args) + client.update_data_agent(**mock_args) # Establish that the underlying call 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/*}/dataAgents" + "%s/v1beta/{data_agent.name=projects/*/locations/*/dataAgents/*}" % client.transport._host, args[1], ) -def test_create_data_agent_rest_flattened_error(transport: str = "rest"): +def test_update_data_agent_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6354,9 +7511,8 @@ def test_create_data_agent_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_data_agent( - data_agent_service.CreateDataAgentRequest(), - parent="parent_value", + client.update_data_agent( + data_agent_service.UpdateDataAgentRequest(), data_agent=gcg_data_agent.DataAgent( data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( staging_context=context.Context( @@ -6364,11 +7520,11 @@ def test_create_data_agent_rest_flattened_error(transport: str = "rest"): ) ) ), - data_agent_id="data_agent_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_create_data_agent_sync_rest_use_cached_wrapped_rpc(): +def test_update_data_agent_sync_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6383,7 +7539,7 @@ def test_create_data_agent_sync_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_data_agent_sync + client._transport.update_data_agent_sync in client._transport._wrapped_methods ) @@ -6392,30 +7548,29 @@ def test_create_data_agent_sync_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_data_agent_sync] = ( + client._transport._wrapped_methods[client._transport.update_data_agent_sync] = ( mock_rpc ) request = {} - client.create_data_agent_sync(request) + client.update_data_agent_sync(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_data_agent_sync(request) + client.update_data_agent_sync(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_data_agent_sync_rest_required_fields( - request_type=data_agent_service.CreateDataAgentRequest, +def test_update_data_agent_sync_rest_required_fields( + request_type=data_agent_service.UpdateDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6425,8 +7580,8 @@ def test_create_data_agent_sync_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseCreateDataAgentSync, - "_BaseCreateDataAgentSync__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseUpdateDataAgentSync, + "_BaseUpdateDataAgentSync__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6436,19 +7591,15 @@ def test_create_data_agent_sync_rest_required_fields( # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "dataAgentId", "requestId", + "updateMask", ) ) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6469,7 +7620,7 @@ def test_create_data_agent_sync_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -6486,14 +7637,14 @@ def test_create_data_agent_sync_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_data_agent_sync(request) + response = client.update_data_agent_sync(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_data_agent_sync_rest_flattened(): +def test_update_data_agent_sync_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6505,11 +7656,14 @@ def test_create_data_agent_sync_rest_flattened(): return_value = gcg_data_agent.DataAgent() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "data_agent": { + "name": "projects/sample1/locations/sample2/dataAgents/sample3" + } + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", data_agent=gcg_data_agent.DataAgent( data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( staging_context=context.Context( @@ -6517,7 +7671,7 @@ def test_create_data_agent_sync_rest_flattened(): ) ) ), - data_agent_id="data_agent_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -6531,20 +7685,20 @@ def test_create_data_agent_sync_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_data_agent_sync(**mock_args) + client.update_data_agent_sync(**mock_args) # Establish that the underlying call 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/*}/dataAgents:createSync" + "%s/v1beta/{data_agent.name=projects/*/locations/*/dataAgents/*}:updateSync" % client.transport._host, args[1], ) -def test_create_data_agent_sync_rest_flattened_error(transport: str = "rest"): +def test_update_data_agent_sync_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6553,9 +7707,8 @@ def test_create_data_agent_sync_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_data_agent_sync( - data_agent_service.CreateDataAgentRequest(), - parent="parent_value", + client.update_data_agent_sync( + data_agent_service.UpdateDataAgentRequest(), data_agent=gcg_data_agent.DataAgent( data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( staging_context=context.Context( @@ -6563,11 +7716,11 @@ def test_create_data_agent_sync_rest_flattened_error(transport: str = "rest"): ) ) ), - data_agent_id="data_agent_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_update_data_agent_rest_use_cached_wrapped_rpc(): +def test_delete_data_agent_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6581,19 +7734,19 @@ def test_update_data_agent_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_data_agent in client._transport._wrapped_methods + assert client._transport.delete_data_agent in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_data_agent] = ( + client._transport._wrapped_methods[client._transport.delete_data_agent] = ( mock_rpc ) request = {} - client.update_data_agent(request) + client.delete_data_agent(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6602,19 +7755,20 @@ def test_update_data_agent_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_data_agent(request) + client.delete_data_agent(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_data_agent_rest_required_fields( - request_type=data_agent_service.UpdateDataAgentRequest, +def test_delete_data_agent_rest_required_fields( + request_type=data_agent_service.DeleteDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6624,8 +7778,8 @@ def test_update_data_agent_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseUpdateDataAgent, - "_BaseUpdateDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseDeleteDataAgent, + "_BaseDeleteDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6635,15 +7789,14 @@ def test_update_data_agent_rest_required_fields( # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "requestId", - "updateMask", - ) - ) + assert not set(unset_fields) - set(("requestId",)) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6664,10 +7817,9 @@ def test_update_data_agent_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -6678,14 +7830,14 @@ def test_update_data_agent_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_data_agent(request) + response = client.delete_data_agent(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_data_agent_rest_flattened(): +def test_delete_data_agent_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6698,21 +7850,12 @@ def test_update_data_agent_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "data_agent": { - "name": "projects/sample1/locations/sample2/dataAgents/sample3" - } + "name": "projects/sample1/locations/sample2/dataAgents/sample3" } # get truthy value for each flattened field mock_args = dict( - data_agent=gcg_data_agent.DataAgent( - data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( - staging_context=context.Context( - system_instruction="system_instruction_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -6724,20 +7867,20 @@ def test_update_data_agent_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_data_agent(**mock_args) + client.delete_data_agent(**mock_args) # Establish that the underlying call 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/{data_agent.name=projects/*/locations/*/dataAgents/*}" + "%s/v1beta/{name=projects/*/locations/*/dataAgents/*}" % client.transport._host, args[1], ) -def test_update_data_agent_rest_flattened_error(transport: str = "rest"): +def test_delete_data_agent_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6746,20 +7889,13 @@ def test_update_data_agent_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_data_agent( - data_agent_service.UpdateDataAgentRequest(), - data_agent=gcg_data_agent.DataAgent( - data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( - staging_context=context.Context( - system_instruction="system_instruction_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_data_agent( + data_agent_service.DeleteDataAgentRequest(), + name="name_value", ) -def test_update_data_agent_sync_rest_use_cached_wrapped_rpc(): +def test_delete_data_agent_sync_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6774,7 +7910,7 @@ def test_update_data_agent_sync_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_data_agent_sync + client._transport.delete_data_agent_sync in client._transport._wrapped_methods ) @@ -6783,29 +7919,30 @@ def test_update_data_agent_sync_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_data_agent_sync] = ( + client._transport._wrapped_methods[client._transport.delete_data_agent_sync] = ( mock_rpc ) request = {} - client.update_data_agent_sync(request) + client.delete_data_agent_sync(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_data_agent_sync(request) + client.delete_data_agent_sync(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_data_agent_sync_rest_required_fields( - request_type=data_agent_service.UpdateDataAgentRequest, +def test_delete_data_agent_sync_rest_required_fields( + request_type=data_agent_service.DeleteDataAgentRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6815,8 +7952,8 @@ def test_update_data_agent_sync_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseUpdateDataAgentSync, - "_BaseUpdateDataAgentSync__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseDeleteDataAgentSync, + "_BaseDeleteDataAgentSync__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -6826,15 +7963,14 @@ def test_update_data_agent_sync_rest_required_fields( # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "requestId", - "updateMask", - ) - ) + assert not set(unset_fields) - set(("requestId",)) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6843,7 +7979,7 @@ def test_update_data_agent_sync_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gcg_data_agent.DataAgent() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -6855,31 +7991,27 @@ def test_update_data_agent_sync_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gcg_data_agent.DataAgent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_data_agent_sync(request) + response = client.delete_data_agent_sync(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_data_agent_sync_rest_flattened(): +def test_delete_data_agent_sync_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6888,52 +8020,41 @@ def test_update_data_agent_sync_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gcg_data_agent.DataAgent() + return_value = None # get arguments that satisfy an http rule for this method sample_request = { - "data_agent": { - "name": "projects/sample1/locations/sample2/dataAgents/sample3" - } + "name": "projects/sample1/locations/sample2/dataAgents/sample3" } # get truthy value for each flattened field mock_args = dict( - data_agent=gcg_data_agent.DataAgent( - data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( - staging_context=context.Context( - system_instruction="system_instruction_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcg_data_agent.DataAgent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_data_agent_sync(**mock_args) + client.delete_data_agent_sync(**mock_args) # Establish that the underlying call 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/{data_agent.name=projects/*/locations/*/dataAgents/*}:updateSync" + "%s/v1beta/{name=projects/*/locations/*/dataAgents/*}:deleteSync" % client.transport._host, args[1], ) -def test_update_data_agent_sync_rest_flattened_error(transport: str = "rest"): +def test_delete_data_agent_sync_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6942,20 +8063,13 @@ def test_update_data_agent_sync_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_data_agent_sync( - data_agent_service.UpdateDataAgentRequest(), - data_agent=gcg_data_agent.DataAgent( - data_analytics_agent=data_analytics_agent.DataAnalyticsAgent( - staging_context=context.Context( - system_instruction="system_instruction_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_data_agent_sync( + data_agent_service.DeleteDataAgentRequest(), + name="name_value", ) -def test_delete_data_agent_rest_use_cached_wrapped_rpc(): +def test_get_iam_policy_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6969,43 +8083,37 @@ def test_delete_data_agent_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_data_agent in client._transport._wrapped_methods + assert client._transport.get_iam_policy in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_data_agent] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_iam_policy] = mock_rpc request = {} - client.delete_data_agent(request) + client.get_iam_policy(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_data_agent(request) + client.get_iam_policy(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_data_agent_rest_required_fields( - request_type=data_agent_service.DeleteDataAgentRequest, +def test_get_iam_policy_rest_required_fields( + request_type=iam_policy_pb2.GetIamPolicyRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["resource"] = "" request = request_type(**request_init) - pb_request = request_type.pb(request) + pb_request = request jsonified_request = json.loads( json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) @@ -7013,8 +8121,8 @@ def test_delete_data_agent_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseDeleteDataAgent, - "_BaseDeleteDataAgent__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetIamPolicy, + "_BaseGetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7024,14 +8132,11 @@ def test_delete_data_agent_rest_required_fields( # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("requestId",)) + jsonified_request["resource"] = "resource_value" # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7040,7 +8145,7 @@ def test_delete_data_agent_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = policy_pb2.Policy() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7049,30 +8154,32 @@ def test_delete_data_agent_rest_required_fields( with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. - pb_request = request_type.pb(request) + pb_request = request transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "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 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_data_agent(request) + response = client.get_iam_policy(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_data_agent_rest_flattened(): +def test_get_iam_policy_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7081,16 +8188,16 @@ def test_delete_data_agent_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = policy_pb2.Policy() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/dataAgents/sample3" + "resource": "projects/sample1/locations/sample2/dataAgents/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + resource="resource_value", ) mock_args.update(sample_request) @@ -7102,20 +8209,20 @@ def test_delete_data_agent_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_data_agent(**mock_args) + client.get_iam_policy(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1beta/{name=projects/*/locations/*/dataAgents/*}" + "%s/v1beta/{resource=projects/*/locations/*/dataAgents/*}:getIamPolicy" % client.transport._host, args[1], ) -def test_delete_data_agent_rest_flattened_error(transport: str = "rest"): +def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7124,13 +8231,13 @@ def test_delete_data_agent_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_data_agent( - data_agent_service.DeleteDataAgentRequest(), - name="name_value", + client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource="resource_value", ) -def test_delete_data_agent_sync_rest_use_cached_wrapped_rpc(): +def test_set_iam_policy_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7144,42 +8251,37 @@ def test_delete_data_agent_sync_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_data_agent_sync - in client._transport._wrapped_methods - ) + assert client._transport.set_iam_policy in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_data_agent_sync] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.set_iam_policy] = mock_rpc request = {} - client.delete_data_agent_sync(request) + client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_data_agent_sync(request) + client.set_iam_policy(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_data_agent_sync_rest_required_fields( - request_type=data_agent_service.DeleteDataAgentRequest, +def test_set_iam_policy_rest_required_fields( + request_type=iam_policy_pb2.SetIamPolicyRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["resource"] = "" request = request_type(**request_init) - pb_request = request_type.pb(request) + pb_request = request jsonified_request = json.loads( json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) @@ -7187,8 +8289,8 @@ def test_delete_data_agent_sync_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseDeleteDataAgentSync, - "_BaseDeleteDataAgentSync__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseSetIamPolicy, + "_BaseSetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7198,14 +8300,11 @@ def test_delete_data_agent_sync_rest_required_fields( # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("requestId",)) + jsonified_request["resource"] = "resource_value" # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7214,7 +8313,7 @@ def test_delete_data_agent_sync_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = policy_pb2.Policy() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7223,30 +8322,32 @@ def test_delete_data_agent_sync_rest_required_fields( with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. - pb_request = request_type.pb(request) + pb_request = request transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "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_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_data_agent_sync(request) + response = client.set_iam_policy(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_data_agent_sync_rest_flattened(): +def test_set_iam_policy_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7255,41 +8356,41 @@ def test_delete_data_agent_sync_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = policy_pb2.Policy() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/dataAgents/sample3" + "resource": "projects/sample1/locations/sample2/dataAgents/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + resource="resource_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_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_data_agent_sync(**mock_args) + client.set_iam_policy(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1beta/{name=projects/*/locations/*/dataAgents/*}:deleteSync" + "%s/v1beta/{resource=projects/*/locations/*/dataAgents/*}:setIamPolicy" % client.transport._host, args[1], ) -def test_delete_data_agent_sync_rest_flattened_error(transport: str = "rest"): +def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7298,13 +8399,13 @@ def test_delete_data_agent_sync_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_data_agent_sync( - data_agent_service.DeleteDataAgentRequest(), - name="name_value", + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource="resource_value", ) -def test_get_iam_policy_rest_use_cached_wrapped_rpc(): +def test_set_agent_ops_observability_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7318,37 +8419,47 @@ def test_get_iam_policy_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_iam_policy in client._transport._wrapped_methods + assert ( + client._transport.set_agent_ops_observability + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_iam_policy] = mock_rpc + client._transport._wrapped_methods[ + client._transport.set_agent_ops_observability + ] = mock_rpc request = {} - client.get_iam_policy(request) + client.set_agent_ops_observability(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_iam_policy(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.set_agent_ops_observability(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_iam_policy_rest_required_fields( - request_type=iam_policy_pb2.GetIamPolicyRequest, +def test_set_agent_ops_observability_rest_required_fields( + request_type=data_agent_service.SetAgentOpsObservabilityRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["resource"] = "" + request_init["parent"] = "" + request_init["data_source_type"] = "" request = request_type(**request_init) - pb_request = request + pb_request = request_type.pb(request) jsonified_request = json.loads( json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) @@ -7356,8 +8467,8 @@ def test_get_iam_policy_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetIamPolicy, - "_BaseGetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseSetAgentOpsObservability, + "_BaseSetAgentOpsObservability__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7367,11 +8478,14 @@ def test_get_iam_policy_rest_required_fields( # verify required fields with default values are now present - jsonified_request["resource"] = "resource_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["dataSourceType"] = "data_source_type_value" # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == "resource_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "dataSourceType" in jsonified_request + assert jsonified_request["dataSourceType"] == "data_source_type_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7380,7 +8494,7 @@ def test_get_iam_policy_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() + 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 @@ -7389,7 +8503,7 @@ def test_get_iam_policy_rest_required_fields( with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. - pb_request = request + pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", "method": "post", @@ -7400,21 +8514,20 @@ def test_get_iam_policy_rest_required_fields( response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_iam_policy(request) + response = client.set_agent_ops_observability(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_iam_policy_rest_flattened(): +def test_set_agent_ops_observability_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7423,16 +8536,16 @@ def test_get_iam_policy_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = { - "resource": "projects/sample1/locations/sample2/dataAgents/sample3" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - resource="resource_value", + parent="parent_value", + telemetry_enabled=True, + data_source_type="data_source_type_value", ) mock_args.update(sample_request) @@ -7444,20 +8557,20 @@ def test_get_iam_policy_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_iam_policy(**mock_args) + client.set_agent_ops_observability(**mock_args) # Establish that the underlying call 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/{resource=projects/*/locations/*/dataAgents/*}:getIamPolicy" + "%s/v1beta/{parent=projects/*/locations/*}/observabilitySettings:setAgentOpsObservability" % client.transport._host, args[1], ) -def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): +def test_set_agent_ops_observability_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7466,13 +8579,15 @@ def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource="resource_value", + client.set_agent_ops_observability( + data_agent_service.SetAgentOpsObservabilityRequest(), + parent="parent_value", + telemetry_enabled=True, + data_source_type="data_source_type_value", ) -def test_set_iam_policy_rest_use_cached_wrapped_rpc(): +def test_retrieve_agent_ops_observability_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7486,46 +8601,53 @@ def test_set_iam_policy_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.set_iam_policy in client._transport._wrapped_methods + assert ( + client._transport.retrieve_agent_ops_observability + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.set_iam_policy] = mock_rpc + client._transport._wrapped_methods[ + client._transport.retrieve_agent_ops_observability + ] = mock_rpc request = {} - client.set_iam_policy(request) + client.retrieve_agent_ops_observability(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.set_iam_policy(request) + client.retrieve_agent_ops_observability(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_set_iam_policy_rest_required_fields( - request_type=iam_policy_pb2.SetIamPolicyRequest, +def test_retrieve_agent_ops_observability_rest_required_fields( + request_type=data_agent_service.RetrieveAgentOpsObservabilityRequest, ): transport_class = transports.DataAgentServiceRestTransport request_init = {} - request_init["resource"] = "" + request_init["parent"] = "" + request_init["data_source_type"] = "" request = request_type(**request_init) - pb_request = request + pb_request = request_type.pb(request) jsonified_request = json.loads( json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) # verify fields with default values are dropped + assert "dataSourceType" not in jsonified_request default_values = getattr( - transport_class._BaseSetIamPolicy, - "_BaseSetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseRetrieveAgentOpsObservability, + "_BaseRetrieveAgentOpsObservability__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -7534,12 +8656,20 @@ def test_set_iam_policy_rest_required_fields( jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "dataSourceType" in jsonified_request + assert jsonified_request["dataSourceType"] == request_init["data_source_type"] - jsonified_request["resource"] = "resource_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["dataSourceType"] = "data_source_type_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("dataSourceType",)) # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == "resource_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "dataSourceType" in jsonified_request + assert jsonified_request["dataSourceType"] == "data_source_type_value" client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7548,7 +8678,7 @@ def test_set_iam_policy_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7557,32 +8687,41 @@ def test_set_iam_policy_rest_required_fields( with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. - pb_request = request + pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.set_iam_policy(request) + response = client.retrieve_agent_ops_observability(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "dataSourceType", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_set_iam_policy_rest_flattened(): +def test_retrieve_agent_ops_observability_rest_flattened(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7591,41 +8730,44 @@ def test_set_iam_policy_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "resource": "projects/sample1/locations/sample2/dataAgents/sample3" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - resource="resource_value", + parent="parent_value", + data_source_type="data_source_type_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.set_iam_policy(**mock_args) + client.retrieve_agent_ops_observability(**mock_args) # Establish that the underlying call 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/{resource=projects/*/locations/*/dataAgents/*}:setIamPolicy" + "%s/v1beta/{parent=projects/*/locations/*}:retrieveAgentOpsObservability" % client.transport._host, args[1], ) -def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): +def test_retrieve_agent_ops_observability_rest_flattened_error(transport: str = "rest"): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7634,9 +8776,10 @@ def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource="resource_value", + client.retrieve_agent_ops_observability( + data_agent_service.RetrieveAgentOpsObservabilityRequest(), + parent="parent_value", + data_source_type="data_source_type_value", ) @@ -7980,6 +9123,50 @@ def test_set_iam_policy_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_agent_ops_observability_empty_call_grpc(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.set_agent_ops_observability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.SetAgentOpsObservabilityRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_retrieve_agent_ops_observability_empty_call_grpc(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + call.return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() + client.retrieve_agent_ops_observability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.RetrieveAgentOpsObservabilityRequest() + assert args[0] == request_msg + + def test_transport_kind_grpc_asyncio(): transport = DataAgentServiceAsyncClient.get_transport_class("grpc_asyncio")( credentials=async_anonymous_credentials() @@ -8068,6 +9255,7 @@ async def test_get_data_agent_empty_call_grpc_asyncio(): display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) ) await client.get_data_agent(request=None) @@ -8125,6 +9313,7 @@ async def test_create_data_agent_sync_empty_call_grpc_asyncio(): display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) ) await client.create_data_agent_sync(request=None) @@ -8182,6 +9371,7 @@ async def test_update_data_agent_sync_empty_call_grpc_asyncio(): display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) ) await client.update_data_agent_sync(request=None) @@ -8297,6 +9487,65 @@ async def test_set_iam_policy_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_set_agent_ops_observability_empty_call_grpc_asyncio(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.set_agent_ops_observability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.SetAgentOpsObservabilityRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_retrieve_agent_ops_observability_empty_call_grpc_asyncio(): + client = DataAgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_agent_service.RetrieveAgentOpsObservabilityResponse( + telemetry_enabled=True, + bigquery_enabled=True, + cloud_trace_enabled=True, + cloud_monitoring_enabled=True, + cloud_logging_enabled=True, + bqaa_enabled=True, + ) + ) + await client.retrieve_agent_ops_observability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.RetrieveAgentOpsObservabilityRequest() + assert args[0] == request_msg + + def test_transport_kind_rest(): transport = DataAgentServiceClient.get_transport_class("rest")( credentials=ga_credentials.AnonymousCredentials() @@ -8634,6 +9883,7 @@ def test_get_data_agent_rest_call_success(request_type): display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) # Wrap the value into a proper Response obj @@ -8654,6 +9904,7 @@ def test_get_data_agent_rest_call_success(request_type): assert response.display_name == "display_name_value" assert response.description == "description_value" assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -8936,6 +10187,25 @@ def test_create_data_agent_rest_call_success(request_type): ], "sorts": ["sorts_value1", "sorts_value2"], "limit": "limit_value", + "dynamic_fields": [ + { + "category": "category_value", + "name": "name_value", + "label": "label_value", + "based_on": "based_on_value", + "type_": "type__value", + "description": "description_value", + "expression": "expression_value", + "filter_expression": "filter_expression_value", + "value_format": "value_format_value", + "value_format_name": "value_format_name_value", + "calculation_type": "calculation_type_value", + "args": ["args_value1", "args_value2"], + "kind_hint": "kind_hint_value", + "type_hint": "type_hint_value", + "is_disabled": True, + } + ], "query_id": "query_id_value", "client_id": "client_id_value", }, @@ -8984,6 +10254,8 @@ def test_create_data_agent_rest_call_success(request_type): "delete_time": {}, "purge_time": {}, "kms_key": "kms_key_value", + "bigquery_agent_analytics_enabled": True, + "bigquery_agent_analytics_table": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -9353,6 +10625,25 @@ def test_create_data_agent_sync_rest_call_success(request_type): ], "sorts": ["sorts_value1", "sorts_value2"], "limit": "limit_value", + "dynamic_fields": [ + { + "category": "category_value", + "name": "name_value", + "label": "label_value", + "based_on": "based_on_value", + "type_": "type__value", + "description": "description_value", + "expression": "expression_value", + "filter_expression": "filter_expression_value", + "value_format": "value_format_value", + "value_format_name": "value_format_name_value", + "calculation_type": "calculation_type_value", + "args": ["args_value1", "args_value2"], + "kind_hint": "kind_hint_value", + "type_hint": "type_hint_value", + "is_disabled": True, + } + ], "query_id": "query_id_value", "client_id": "client_id_value", }, @@ -9401,6 +10692,8 @@ def test_create_data_agent_sync_rest_call_success(request_type): "delete_time": {}, "purge_time": {}, "kms_key": "kms_key_value", + "bigquery_agent_analytics_enabled": True, + "bigquery_agent_analytics_table": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -9479,6 +10772,7 @@ def get_message_fields(field): display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, ) # Wrap the value into a proper Response obj @@ -9499,6 +10793,7 @@ def get_message_fields(field): assert response.display_name == "display_name_value" assert response.description == "description_value" assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -9785,6 +11080,25 @@ def test_update_data_agent_rest_call_success(request_type): ], "sorts": ["sorts_value1", "sorts_value2"], "limit": "limit_value", + "dynamic_fields": [ + { + "category": "category_value", + "name": "name_value", + "label": "label_value", + "based_on": "based_on_value", + "type_": "type__value", + "description": "description_value", + "expression": "expression_value", + "filter_expression": "filter_expression_value", + "value_format": "value_format_value", + "value_format_name": "value_format_name_value", + "calculation_type": "calculation_type_value", + "args": ["args_value1", "args_value2"], + "kind_hint": "kind_hint_value", + "type_hint": "type_hint_value", + "is_disabled": True, + } + ], "query_id": "query_id_value", "client_id": "client_id_value", }, @@ -9833,6 +11147,8 @@ def test_update_data_agent_rest_call_success(request_type): "delete_time": {}, "purge_time": {}, "kms_key": "kms_key_value", + "bigquery_agent_analytics_enabled": True, + "bigquery_agent_analytics_table": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -10206,6 +11522,25 @@ def test_update_data_agent_sync_rest_call_success(request_type): ], "sorts": ["sorts_value1", "sorts_value2"], "limit": "limit_value", + "dynamic_fields": [ + { + "category": "category_value", + "name": "name_value", + "label": "label_value", + "based_on": "based_on_value", + "type_": "type__value", + "description": "description_value", + "expression": "expression_value", + "filter_expression": "filter_expression_value", + "value_format": "value_format_value", + "value_format_name": "value_format_name_value", + "calculation_type": "calculation_type_value", + "args": ["args_value1", "args_value2"], + "kind_hint": "kind_hint_value", + "type_hint": "type_hint_value", + "is_disabled": True, + } + ], "query_id": "query_id_value", "client_id": "client_id_value", }, @@ -10254,6 +11589,8 @@ def test_update_data_agent_sync_rest_call_success(request_type): "delete_time": {}, "purge_time": {}, "kms_key": "kms_key_value", + "bigquery_agent_analytics_enabled": True, + "bigquery_agent_analytics_table": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -10332,30 +11669,283 @@ def get_message_fields(field): display_name="display_name_value", description="description_value", kms_key="kms_key_value", + bigquery_agent_analytics_enabled=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcg_data_agent.DataAgent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_data_agent_sync(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcg_data_agent.DataAgent) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.kms_key == "kms_key_value" + assert response.bigquery_agent_analytics_enabled is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_data_agent_sync_rest_interceptors(null_interceptor): + transport = transports.DataAgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DataAgentServiceRestInterceptor(), + ) + client = DataAgentServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DataAgentServiceRestInterceptor, "post_update_data_agent_sync" + ) as post, + mock.patch.object( + transports.DataAgentServiceRestInterceptor, + "post_update_data_agent_sync_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DataAgentServiceRestInterceptor, "pre_update_data_agent_sync" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = data_agent_service.UpdateDataAgentRequest.pb( + data_agent_service.UpdateDataAgentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcg_data_agent.DataAgent.to_json(gcg_data_agent.DataAgent()) + req.return_value.content = return_value + + request = data_agent_service.UpdateDataAgentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcg_data_agent.DataAgent() + post_with_metadata.return_value = gcg_data_agent.DataAgent(), metadata + + client.update_data_agent_sync( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_data_agent_rest_bad_request( + request_type=data_agent_service.DeleteDataAgentRequest, +): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/dataAgents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_data_agent(request) + + +@pytest.mark.parametrize( + "request_type", + [ + data_agent_service.DeleteDataAgentRequest, + dict, + ], +) +def test_delete_data_agent_rest_call_success(request_type): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/dataAgents/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 = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_data_agent(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_data_agent_rest_interceptors(null_interceptor): + transport = transports.DataAgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DataAgentServiceRestInterceptor(), + ) + client = DataAgentServiceClient(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.DataAgentServiceRestInterceptor, "post_delete_data_agent" + ) as post, + mock.patch.object( + transports.DataAgentServiceRestInterceptor, + "post_delete_data_agent_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DataAgentServiceRestInterceptor, "pre_delete_data_agent" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = data_agent_service.DeleteDataAgentRequest.pb( + data_agent_service.DeleteDataAgentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = data_agent_service.DeleteDataAgentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_data_agent( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_data_agent_sync_rest_bad_request( + request_type=data_agent_service.DeleteDataAgentRequest, +): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/dataAgents/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_data_agent_sync(request) + + +@pytest.mark.parametrize( + "request_type", + [ + data_agent_service.DeleteDataAgentRequest, + dict, + ], +) +def test_delete_data_agent_sync_rest_call_success(request_type): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/dataAgents/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 = mock.Mock() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gcg_data_agent.DataAgent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_data_agent_sync(request) + response = client.delete_data_agent_sync(request) # Establish that the response is the type that we expect. - assert isinstance(response, gcg_data_agent.DataAgent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.kms_key == "kms_key_value" + assert response is None @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_data_agent_sync_rest_interceptors(null_interceptor): +def test_delete_data_agent_sync_rest_interceptors(null_interceptor): transport = transports.DataAgentServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10368,21 +11958,12 @@ def test_update_data_agent_sync_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.DataAgentServiceRestInterceptor, "post_update_data_agent_sync" - ) as post, - mock.patch.object( - transports.DataAgentServiceRestInterceptor, - "post_update_data_agent_sync_with_metadata", - ) as post_with_metadata, - mock.patch.object( - transports.DataAgentServiceRestInterceptor, "pre_update_data_agent_sync" + transports.DataAgentServiceRestInterceptor, "pre_delete_data_agent_sync" ) as pre, ): pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = data_agent_service.UpdateDataAgentRequest.pb( - data_agent_service.UpdateDataAgentRequest() + pb_message = data_agent_service.DeleteDataAgentRequest.pb( + data_agent_service.DeleteDataAgentRequest() ) transcode.return_value = { "method": "post", @@ -10394,19 +11975,15 @@ def test_update_data_agent_sync_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = gcg_data_agent.DataAgent.to_json(gcg_data_agent.DataAgent()) - req.return_value.content = return_value - request = data_agent_service.UpdateDataAgentRequest() + request = data_agent_service.DeleteDataAgentRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gcg_data_agent.DataAgent() - post_with_metadata.return_value = gcg_data_agent.DataAgent(), metadata - client.update_data_agent_sync( + client.delete_data_agent_sync( request, metadata=[ ("key", "val"), @@ -10415,18 +11992,16 @@ def test_update_data_agent_sync_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() -def test_delete_data_agent_rest_bad_request( - request_type=data_agent_service.DeleteDataAgentRequest, +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, ): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/dataAgents/sample3"} + request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10442,29 +12017,32 @@ def test_delete_data_agent_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_data_agent(request) + client.get_iam_policy(request) @pytest.mark.parametrize( "request_type", [ - data_agent_service.DeleteDataAgentRequest, + iam_policy_pb2.GetIamPolicyRequest, dict, ], ) -def test_delete_data_agent_rest_call_success(request_type): +def test_get_iam_policy_rest_call_success(request_type): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/dataAgents/sample3"} + request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -10473,14 +12051,16 @@ def test_delete_data_agent_rest_call_success(request_type): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_data_agent(request) + response = client.get_iam_policy(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_data_agent_rest_interceptors(null_interceptor): +def test_get_iam_policy_rest_interceptors(null_interceptor): transport = transports.DataAgentServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10492,24 +12072,21 @@ def test_delete_data_agent_rest_interceptors(null_interceptor): 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.DataAgentServiceRestInterceptor, "post_delete_data_agent" + transports.DataAgentServiceRestInterceptor, "post_get_iam_policy" ) as post, mock.patch.object( transports.DataAgentServiceRestInterceptor, - "post_delete_data_agent_with_metadata", + "post_get_iam_policy_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DataAgentServiceRestInterceptor, "pre_delete_data_agent" + transports.DataAgentServiceRestInterceptor, "pre_get_iam_policy" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = data_agent_service.DeleteDataAgentRequest.pb( - data_agent_service.DeleteDataAgentRequest() - ) + pb_message = iam_policy_pb2.GetIamPolicyRequest() transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10520,19 +12097,19 @@ def test_delete_data_agent_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) + return_value = json_format.MessageToJson(policy_pb2.Policy()) req.return_value.content = return_value - request = data_agent_service.DeleteDataAgentRequest() + request = iam_policy_pb2.GetIamPolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + post.return_value = policy_pb2.Policy() + post_with_metadata.return_value = policy_pb2.Policy(), metadata - client.delete_data_agent( + client.get_iam_policy( request, metadata=[ ("key", "val"), @@ -10545,14 +12122,14 @@ def test_delete_data_agent_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_data_agent_sync_rest_bad_request( - request_type=data_agent_service.DeleteDataAgentRequest, +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, ): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/dataAgents/sample3"} + request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10568,45 +12145,50 @@ def test_delete_data_agent_sync_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_data_agent_sync(request) + client.set_iam_policy(request) @pytest.mark.parametrize( "request_type", [ - data_agent_service.DeleteDataAgentRequest, + iam_policy_pb2.SetIamPolicyRequest, dict, ], ) -def test_delete_data_agent_sync_rest_call_success(request_type): +def test_set_iam_policy_rest_call_success(request_type): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/dataAgents/sample3"} + request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/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 + return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" + json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_data_agent_sync(request) + response = client.set_iam_policy(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_data_agent_sync_rest_interceptors(null_interceptor): +def test_set_iam_policy_rest_interceptors(null_interceptor): transport = transports.DataAgentServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10619,13 +12201,20 @@ def test_delete_data_agent_sync_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.DataAgentServiceRestInterceptor, "pre_delete_data_agent_sync" + transports.DataAgentServiceRestInterceptor, "post_set_iam_policy" + ) as post, + mock.patch.object( + transports.DataAgentServiceRestInterceptor, + "post_set_iam_policy_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DataAgentServiceRestInterceptor, "pre_set_iam_policy" ) as pre, ): pre.assert_not_called() - pb_message = data_agent_service.DeleteDataAgentRequest.pb( - data_agent_service.DeleteDataAgentRequest() - ) + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10636,15 +12225,19 @@ def test_delete_data_agent_sync_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(policy_pb2.Policy()) + req.return_value.content = return_value - request = data_agent_service.DeleteDataAgentRequest() + request = iam_policy_pb2.SetIamPolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + post_with_metadata.return_value = policy_pb2.Policy(), metadata - client.delete_data_agent_sync( + client.set_iam_policy( request, metadata=[ ("key", "val"), @@ -10653,16 +12246,18 @@ def test_delete_data_agent_sync_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_get_iam_policy_rest_bad_request( - request_type=iam_policy_pb2.GetIamPolicyRequest, +def test_set_agent_ops_observability_rest_bad_request( + request_type=data_agent_service.SetAgentOpsObservabilityRequest, ): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} + 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. @@ -10678,32 +12273,29 @@ def test_get_iam_policy_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_iam_policy(request) + client.set_agent_ops_observability(request) @pytest.mark.parametrize( "request_type", [ - iam_policy_pb2.GetIamPolicyRequest, + data_agent_service.SetAgentOpsObservabilityRequest, dict, ], ) -def test_get_iam_policy_rest_call_success(request_type): +def test_set_agent_ops_observability_rest_call_success(request_type): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} + 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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -10712,16 +12304,14 @@ def test_get_iam_policy_rest_call_success(request_type): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_iam_policy(request) + response = client.set_agent_ops_observability(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" + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): +def test_set_agent_ops_observability_rest_interceptors(null_interceptor): transport = transports.DataAgentServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10733,21 +12323,26 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): 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.DataAgentServiceRestInterceptor, "post_get_iam_policy" + transports.DataAgentServiceRestInterceptor, + "post_set_agent_ops_observability", ) as post, mock.patch.object( transports.DataAgentServiceRestInterceptor, - "post_get_iam_policy_with_metadata", + "post_set_agent_ops_observability_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DataAgentServiceRestInterceptor, "pre_get_iam_policy" + transports.DataAgentServiceRestInterceptor, + "pre_set_agent_ops_observability", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() + pb_message = data_agent_service.SetAgentOpsObservabilityRequest.pb( + data_agent_service.SetAgentOpsObservabilityRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10758,19 +12353,19 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(policy_pb2.Policy()) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = iam_policy_pb2.GetIamPolicyRequest() + request = data_agent_service.SetAgentOpsObservabilityRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - post_with_metadata.return_value = policy_pb2.Policy(), metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.get_iam_policy( + client.set_agent_ops_observability( request, metadata=[ ("key", "val"), @@ -10783,14 +12378,14 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_set_iam_policy_rest_bad_request( - request_type=iam_policy_pb2.SetIamPolicyRequest, +def test_retrieve_agent_ops_observability_rest_bad_request( + request_type=data_agent_service.RetrieveAgentOpsObservabilityRequest, ): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} + 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. @@ -10806,50 +12401,65 @@ def test_set_iam_policy_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.set_iam_policy(request) + client.retrieve_agent_ops_observability(request) @pytest.mark.parametrize( "request_type", [ - iam_policy_pb2.SetIamPolicyRequest, + data_agent_service.RetrieveAgentOpsObservabilityRequest, dict, ], ) -def test_set_iam_policy_rest_call_success(request_type): +def test_retrieve_agent_ops_observability_rest_call_success(request_type): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/dataAgents/sample3"} + 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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse( + telemetry_enabled=True, + bigquery_enabled=True, + cloud_trace_enabled=True, + cloud_monitoring_enabled=True, + cloud_logging_enabled=True, + bqaa_enabled=True, ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.set_iam_policy(request) + response = client.retrieve_agent_ops_observability(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" + assert isinstance( + response, data_agent_service.RetrieveAgentOpsObservabilityResponse + ) + assert response.telemetry_enabled is True + assert response.bigquery_enabled is True + assert response.cloud_trace_enabled is True + assert response.cloud_monitoring_enabled is True + assert response.cloud_logging_enabled is True + assert response.bqaa_enabled is True @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): +def test_retrieve_agent_ops_observability_rest_interceptors(null_interceptor): transport = transports.DataAgentServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10862,20 +12472,24 @@ def test_set_iam_policy_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.DataAgentServiceRestInterceptor, "post_set_iam_policy" + transports.DataAgentServiceRestInterceptor, + "post_retrieve_agent_ops_observability", ) as post, mock.patch.object( transports.DataAgentServiceRestInterceptor, - "post_set_iam_policy_with_metadata", + "post_retrieve_agent_ops_observability_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DataAgentServiceRestInterceptor, "pre_set_iam_policy" + transports.DataAgentServiceRestInterceptor, + "pre_retrieve_agent_ops_observability", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() + pb_message = data_agent_service.RetrieveAgentOpsObservabilityRequest.pb( + data_agent_service.RetrieveAgentOpsObservabilityRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10886,19 +12500,24 @@ def test_set_iam_policy_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(policy_pb2.Policy()) + return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse.to_json( + data_agent_service.RetrieveAgentOpsObservabilityResponse() + ) req.return_value.content = return_value - request = iam_policy_pb2.SetIamPolicyRequest() + request = data_agent_service.RetrieveAgentOpsObservabilityRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - post_with_metadata.return_value = policy_pb2.Policy(), metadata + post.return_value = data_agent_service.RetrieveAgentOpsObservabilityResponse() + post_with_metadata.return_value = ( + data_agent_service.RetrieveAgentOpsObservabilityResponse(), + metadata, + ) - client.set_iam_policy( + client.retrieve_agent_ops_observability( request, metadata=[ ("key", "val"), @@ -11515,6 +13134,48 @@ def test_set_iam_policy_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_agent_ops_observability_empty_call_rest(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_agent_ops_observability), "__call__" + ) as call: + client.set_agent_ops_observability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.SetAgentOpsObservabilityRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_retrieve_agent_ops_observability_empty_call_rest(): + client = DataAgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_agent_ops_observability), "__call__" + ) as call: + client.retrieve_agent_ops_observability(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_agent_service.RetrieveAgentOpsObservabilityRequest() + assert args[0] == request_msg + + def test_data_agent_service_rest_lro_client(): client = DataAgentServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11576,6 +13237,8 @@ def test_data_agent_service_base_transport(): "delete_data_agent_sync", "get_iam_policy", "set_iam_policy", + "set_agent_ops_observability", + "retrieve_agent_ops_observability", "get_location", "list_locations", "get_operation", @@ -11885,6 +13548,12 @@ def test_data_agent_service_client_transport_session_collision(transport_name): session1 = client1.transport.set_iam_policy._session session2 = client2.transport.set_iam_policy._session assert session1 != session2 + session1 = client1.transport.set_agent_ops_observability._session + session2 = client2.transport.set_agent_ops_observability._session + assert session1 != session2 + session1 = client1.transport.retrieve_agent_ops_observability._session + session2 = client2.transport.retrieve_agent_ops_observability._session + assert session1 != session2 def test_data_agent_service_grpc_transport_channel(): diff --git a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_chat_service.py b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_chat_service.py index e763438a7e50..1ac151266840 100644 --- a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_chat_service.py +++ b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_chat_service.py @@ -39,6 +39,7 @@ HAS_GOOGLE_AUTH_AIO = False import google.auth +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.struct_pb2 as struct_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import google.protobuf.wrappers_pb2 as wrappers_pb2 # type: ignore @@ -70,6 +71,7 @@ credentials, data_chat_service, datasource, + usage, ) from google.cloud.geminidataanalytics_v1beta.types import ( conversation as gcg_conversation, @@ -1359,8 +1361,8 @@ def test_create_conversation(request_type, transport: str = "grpc"): call.return_value = gcg_conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", kms_key="kms_key_value", - memory_paused=True, ) response = client.create_conversation(request) @@ -1374,8 +1376,8 @@ def test_create_conversation(request_type, transport: str = "grpc"): assert isinstance(response, gcg_conversation.Conversation) assert response.name == "name_value" assert response.agents == ["agents_value"] + assert response.title == "title_value" assert response.kms_key == "kms_key_value" - assert response.memory_paused is True def test_create_conversation_non_empty_request_with_auto_populated_field(): @@ -1519,8 +1521,8 @@ async def test_create_conversation_async(request_type, transport: str = "grpc_as gcg_conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", kms_key="kms_key_value", - memory_paused=True, ) ) response = await client.create_conversation(request) @@ -1535,8 +1537,8 @@ async def test_create_conversation_async(request_type, transport: str = "grpc_as assert isinstance(response, gcg_conversation.Conversation) assert response.name == "name_value" assert response.agents == ["agents_value"] + assert response.title == "title_value" assert response.kms_key == "kms_key_value" - assert response.memory_paused is True def test_create_conversation_field_headers(): @@ -2040,6 +2042,366 @@ async def test_delete_conversation_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + gcg_conversation.UpdateConversationRequest(), + {}, + ], +) +def test_update_conversation(request_type, transport: str = "grpc"): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcg_conversation.Conversation( + name="name_value", + agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", + ) + response = client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcg_conversation.UpdateConversationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcg_conversation.Conversation) + assert response.name == "name_value" + assert response.agents == ["agents_value"] + assert response.title == "title_value" + assert response.kms_key == "kms_key_value" + + +def test_update_conversation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcg_conversation.UpdateConversationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_conversation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcg_conversation.UpdateConversationRequest() + assert args[0] == request_msg + + +def test_update_conversation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_conversation in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_conversation] = ( + mock_rpc + ) + request = {} + client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_conversation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_conversation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DataChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_conversation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_conversation + ] = mock_rpc + + request = {} + await client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_conversation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + gcg_conversation.UpdateConversationRequest(), + {}, + ], +) +async def test_update_conversation_async(request_type, transport: str = "grpc_asyncio"): + client = DataChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcg_conversation.Conversation( + name="name_value", + agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", + ) + ) + response = await client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcg_conversation.UpdateConversationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcg_conversation.Conversation) + assert response.name == "name_value" + assert response.agents == ["agents_value"] + assert response.title == "title_value" + assert response.kms_key == "kms_key_value" + + +def test_update_conversation_field_headers(): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcg_conversation.UpdateConversationRequest() + + request.conversation.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + call.return_value = gcg_conversation.Conversation() + client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "conversation.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_conversation_field_headers_async(): + client = DataChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcg_conversation.UpdateConversationRequest() + + request.conversation.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcg_conversation.Conversation() + ) + await client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "conversation.name=name_value", + ) in kw["metadata"] + + +def test_update_conversation_flattened(): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcg_conversation.Conversation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_conversation( + conversation=gcg_conversation.Conversation(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].conversation + mock_val = gcg_conversation.Conversation(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_conversation_flattened_error(): + client = DataChatServiceClient( + credentials=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_conversation( + gcg_conversation.UpdateConversationRequest(), + conversation=gcg_conversation.Conversation(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_conversation_flattened_async(): + client = DataChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcg_conversation.Conversation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcg_conversation.Conversation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_conversation( + conversation=gcg_conversation.Conversation(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].conversation + mock_val = gcg_conversation.Conversation(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_conversation_flattened_error_async(): + client = DataChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_conversation( + gcg_conversation.UpdateConversationRequest(), + conversation=gcg_conversation.Conversation(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + @pytest.mark.parametrize( "request_type", [ @@ -2063,8 +2425,8 @@ def test_get_conversation(request_type, transport: str = "grpc"): call.return_value = conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", kms_key="kms_key_value", - memory_paused=True, ) response = client.get_conversation(request) @@ -2078,8 +2440,8 @@ def test_get_conversation(request_type, transport: str = "grpc"): assert isinstance(response, conversation.Conversation) assert response.name == "name_value" assert response.agents == ["agents_value"] + assert response.title == "title_value" assert response.kms_key == "kms_key_value" - assert response.memory_paused is True def test_get_conversation_non_empty_request_with_auto_populated_field(): @@ -2215,8 +2577,8 @@ async def test_get_conversation_async(request_type, transport: str = "grpc_async conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", kms_key="kms_key_value", - memory_paused=True, ) ) response = await client.get_conversation(request) @@ -2231,8 +2593,8 @@ async def test_get_conversation_async(request_type, transport: str = "grpc_async assert isinstance(response, conversation.Conversation) assert response.name == "name_value" assert response.agents == ["agents_value"] + assert response.title == "title_value" assert response.kms_key == "kms_key_value" - assert response.memory_paused is True def test_get_conversation_field_headers(): @@ -4173,6 +4535,189 @@ def test_delete_conversation_rest_flattened_error(transport: str = "rest"): ) +def test_update_conversation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_conversation in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_conversation] = ( + mock_rpc + ) + + request = {} + client.update_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_conversation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_conversation_rest_required_fields( + request_type=gcg_conversation.UpdateConversationRequest, +): + transport_class = transports.DataChatServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateConversation, + "_BaseUpdateConversation__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcg_conversation.Conversation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcg_conversation.Conversation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_conversation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_conversation_rest_flattened(): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcg_conversation.Conversation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "conversation": { + "name": "projects/sample1/locations/sample2/conversations/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + conversation=gcg_conversation.Conversation(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcg_conversation.Conversation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_conversation(**mock_args) + + # Establish that the underlying call 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/{conversation.name=projects/*/locations/*/conversations/*}" + % client.transport._host, + args[1], + ) + + +def test_update_conversation_rest_flattened_error(transport: str = "rest"): + client = DataChatServiceClient( + credentials=ga_credentials.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_conversation( + gcg_conversation.UpdateConversationRequest(), + conversation=gcg_conversation.Conversation(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + def test_get_conversation_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5102,13 +5647,35 @@ def test_create_conversation_empty_call_grpc(): # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = gcg_conversation.CreateConversationRequest() + request_msg = gcg_conversation.CreateConversationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_conversation_empty_call_grpc(): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), "__call__" + ) as call: + call.return_value = None + client.delete_conversation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = conversation.DeleteConversationRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_delete_conversation_empty_call_grpc(): +def test_update_conversation_empty_call_grpc(): client = DataChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", @@ -5116,15 +5683,15 @@ def test_delete_conversation_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_conversation), "__call__" + type(client.transport.update_conversation), "__call__" ) as call: - call.return_value = None - client.delete_conversation(request=None) + call.return_value = gcg_conversation.Conversation() + client.update_conversation(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = conversation.DeleteConversationRequest() + request_msg = gcg_conversation.UpdateConversationRequest() assert args[0] == request_msg @@ -5267,8 +5834,8 @@ async def test_create_conversation_empty_call_grpc_asyncio(): gcg_conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", kms_key="kms_key_value", - memory_paused=True, ) ) await client.create_conversation(request=None) @@ -5304,6 +5871,37 @@ async def test_delete_conversation_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_conversation_empty_call_grpc_asyncio(): + client = DataChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcg_conversation.Conversation( + name="name_value", + agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", + ) + ) + await client.update_conversation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcg_conversation.UpdateConversationRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio @@ -5320,8 +5918,8 @@ async def test_get_conversation_empty_call_grpc_asyncio(): conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", kms_key="kms_key_value", - memory_paused=True, ) ) await client.get_conversation(request=None) @@ -5597,8 +6195,8 @@ def test_create_conversation_rest_call_success(request_type): "create_time": {"seconds": 751, "nanos": 543}, "last_used_time": {}, "labels": {}, + "title": "title_value", "kms_key": "kms_key_value", - "memory_paused": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -5675,8 +6273,8 @@ def get_message_fields(field): return_value = gcg_conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", kms_key="kms_key_value", - memory_paused=True, ) # Wrap the value into a proper Response obj @@ -5695,8 +6293,8 @@ def get_message_fields(field): assert isinstance(response, gcg_conversation.Conversation) assert response.name == "name_value" assert response.agents == ["agents_value"] + assert response.title == "title_value" assert response.kms_key == "kms_key_value" - assert response.memory_paused is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -5876,6 +6474,229 @@ def test_delete_conversation_rest_interceptors(null_interceptor): pre.assert_called_once() +def test_update_conversation_rest_bad_request( + request_type=gcg_conversation.UpdateConversationRequest, +): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "conversation": { + "name": "projects/sample1/locations/sample2/conversations/sample3" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_conversation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcg_conversation.UpdateConversationRequest, + dict, + ], +) +def test_update_conversation_rest_call_success(request_type): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "conversation": { + "name": "projects/sample1/locations/sample2/conversations/sample3" + } + } + request_init["conversation"] = { + "name": "projects/sample1/locations/sample2/conversations/sample3", + "agents": ["agents_value1", "agents_value2"], + "create_time": {"seconds": 751, "nanos": 543}, + "last_used_time": {}, + "labels": {}, + "title": "title_value", + "kms_key": "kms_key_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcg_conversation.UpdateConversationRequest.meta.fields["conversation"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["conversation"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["conversation"][field])): + del request_init["conversation"][field][i][subfield] + else: + del request_init["conversation"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcg_conversation.Conversation( + name="name_value", + agents=["agents_value"], + title="title_value", + kms_key="kms_key_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcg_conversation.Conversation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_conversation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcg_conversation.Conversation) + assert response.name == "name_value" + assert response.agents == ["agents_value"] + assert response.title == "title_value" + assert response.kms_key == "kms_key_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_conversation_rest_interceptors(null_interceptor): + transport = transports.DataChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DataChatServiceRestInterceptor(), + ) + client = DataChatServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DataChatServiceRestInterceptor, "post_update_conversation" + ) as post, + mock.patch.object( + transports.DataChatServiceRestInterceptor, + "post_update_conversation_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DataChatServiceRestInterceptor, "pre_update_conversation" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcg_conversation.UpdateConversationRequest.pb( + gcg_conversation.UpdateConversationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcg_conversation.Conversation.to_json( + gcg_conversation.Conversation() + ) + req.return_value.content = return_value + + request = gcg_conversation.UpdateConversationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcg_conversation.Conversation() + post_with_metadata.return_value = gcg_conversation.Conversation(), metadata + + client.update_conversation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_get_conversation_rest_bad_request( request_type=conversation.GetConversationRequest, ): @@ -5924,8 +6745,8 @@ def test_get_conversation_rest_call_success(request_type): return_value = conversation.Conversation( name="name_value", agents=["agents_value"], + title="title_value", kms_key="kms_key_value", - memory_paused=True, ) # Wrap the value into a proper Response obj @@ -5944,8 +6765,8 @@ def test_get_conversation_rest_call_success(request_type): assert isinstance(response, conversation.Conversation) assert response.name == "name_value" assert response.agents == ["agents_value"] + assert response.title == "title_value" assert response.kms_key == "kms_key_value" - assert response.memory_paused is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -6870,6 +7691,27 @@ def test_delete_conversation_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_conversation_empty_call_rest(): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), "__call__" + ) as call: + client.update_conversation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcg_conversation.UpdateConversationRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_get_conversation_empty_call_rest(): @@ -6984,6 +7826,7 @@ def test_data_chat_service_base_transport(): "chat", "create_conversation", "delete_conversation", + "update_conversation", "get_conversation", "list_conversations", "list_messages", @@ -7268,6 +8111,9 @@ def test_data_chat_service_client_transport_session_collision(transport_name): session1 = client1.transport.delete_conversation._session session2 = client2.transport.delete_conversation._session assert session1 != session2 + session1 = client1.transport.update_conversation._session + session2 = client2.transport.update_conversation._session + assert session1 != session2 session1 = client1.transport.get_conversation._session session2 = client2.transport.get_conversation._session assert session1 != session2 diff --git a/packages/google-cloud-lustre/google/cloud/lustre/__init__.py b/packages/google-cloud-lustre/google/cloud/lustre/__init__.py index 11508dbdb8dc..919e2915eb29 100644 --- a/packages/google-cloud-lustre/google/cloud/lustre/__init__.py +++ b/packages/google-cloud-lustre/google/cloud/lustre/__init__.py @@ -20,16 +20,39 @@ from google.cloud.lustre_v1.services.lustre.async_client import LustreAsyncClient from google.cloud.lustre_v1.services.lustre.client import LustreClient +from google.cloud.lustre_v1.types.directory_policy import ( + CreateDirectoryPolicyRequest, + DeleteDirectoryPolicyRequest, + DirectoryPolicy, + GetDirectoryPolicyRequest, + ListDirectoryPoliciesRequest, + ListDirectoryPoliciesResponse, +) from google.cloud.lustre_v1.types.instance import ( + AccessRulesOptions, CreateInstanceRequest, DeleteInstanceRequest, + DynamicTierOptions, GetInstanceRequest, Instance, ListInstancesRequest, ListInstancesResponse, + MaintenancePolicy, + MaintenanceSchedule, OperationMetadata, + RescheduleMaintenanceRequest, UpdateInstanceRequest, ) +from google.cloud.lustre_v1.types.mirror import ( + CreateMirrorMetadata, + CreateMirrorRequest, + DeleteMirrorRequest, + GetMirrorRequest, + ListMirrorsRequest, + ListMirrorsResponse, + Mirror, + UpdateMirrorRequest, +) from google.cloud.lustre_v1.types.transfer import ( ErrorLogEntry, ErrorSummary, @@ -49,14 +72,33 @@ __all__ = ( "LustreClient", "LustreAsyncClient", + "CreateDirectoryPolicyRequest", + "DeleteDirectoryPolicyRequest", + "DirectoryPolicy", + "GetDirectoryPolicyRequest", + "ListDirectoryPoliciesRequest", + "ListDirectoryPoliciesResponse", + "AccessRulesOptions", "CreateInstanceRequest", "DeleteInstanceRequest", + "DynamicTierOptions", "GetInstanceRequest", "Instance", "ListInstancesRequest", "ListInstancesResponse", + "MaintenancePolicy", + "MaintenanceSchedule", "OperationMetadata", + "RescheduleMaintenanceRequest", "UpdateInstanceRequest", + "CreateMirrorMetadata", + "CreateMirrorRequest", + "DeleteMirrorRequest", + "GetMirrorRequest", + "ListMirrorsRequest", + "ListMirrorsResponse", + "Mirror", + "UpdateMirrorRequest", "ErrorLogEntry", "ErrorSummary", "ExportDataMetadata", diff --git a/packages/google-cloud-lustre/google/cloud/lustre_v1/__init__.py b/packages/google-cloud-lustre/google/cloud/lustre_v1/__init__.py index 0927c415f2dd..b16b39568232 100644 --- a/packages/google-cloud-lustre/google/cloud/lustre_v1/__init__.py +++ b/packages/google-cloud-lustre/google/cloud/lustre_v1/__init__.py @@ -27,23 +27,48 @@ # Older Python versions safely ignore this variable. __lazy_modules__ = { "google.cloud.lustre_v1.services.lustre", + "google.cloud.lustre_v1.types.directory_policy", "google.cloud.lustre_v1.types.instance", "google.cloud.lustre_v1.types.lustre", + "google.cloud.lustre_v1.types.mirror", "google.cloud.lustre_v1.types.transfer", } from .services.lustre import LustreAsyncClient, LustreClient +from .types.directory_policy import ( + CreateDirectoryPolicyRequest, + DeleteDirectoryPolicyRequest, + DirectoryPolicy, + GetDirectoryPolicyRequest, + ListDirectoryPoliciesRequest, + ListDirectoryPoliciesResponse, +) from .types.instance import ( + AccessRulesOptions, CreateInstanceRequest, DeleteInstanceRequest, + DynamicTierOptions, GetInstanceRequest, Instance, ListInstancesRequest, ListInstancesResponse, + MaintenancePolicy, + MaintenanceSchedule, OperationMetadata, + RescheduleMaintenanceRequest, UpdateInstanceRequest, ) +from .types.mirror import ( + CreateMirrorMetadata, + CreateMirrorRequest, + DeleteMirrorRequest, + GetMirrorRequest, + ListMirrorsRequest, + ListMirrorsResponse, + Mirror, + UpdateMirrorRequest, +) from .types.transfer import ( ErrorLogEntry, ErrorSummary, @@ -62,28 +87,47 @@ __all__ = ( "LustreAsyncClient", + "AccessRulesOptions", + "CreateDirectoryPolicyRequest", "CreateInstanceRequest", + "CreateMirrorMetadata", + "CreateMirrorRequest", + "DeleteDirectoryPolicyRequest", "DeleteInstanceRequest", + "DeleteMirrorRequest", + "DirectoryPolicy", + "DynamicTierOptions", "ErrorLogEntry", "ErrorSummary", "ExportDataMetadata", "ExportDataRequest", "ExportDataResponse", "GcsPath", + "GetDirectoryPolicyRequest", "GetInstanceRequest", + "GetMirrorRequest", "ImportDataMetadata", "ImportDataRequest", "ImportDataResponse", "Instance", + "ListDirectoryPoliciesRequest", + "ListDirectoryPoliciesResponse", "ListInstancesRequest", "ListInstancesResponse", + "ListMirrorsRequest", + "ListMirrorsResponse", "LustreClient", "LustrePath", + "MaintenancePolicy", + "MaintenanceSchedule", + "Mirror", "OperationMetadata", + "RescheduleMaintenanceRequest", "TransferCounters", "TransferOperationMetadata", "TransferType", "UpdateInstanceRequest", + "UpdateMirrorRequest", ) api_core.check_python_version("google.cloud.lustre_v1") diff --git a/packages/google-cloud-lustre/google/cloud/lustre_v1/gapic_metadata.json b/packages/google-cloud-lustre/google/cloud/lustre_v1/gapic_metadata.json index 3cb8ac63af86..fbdd3db8528f 100644 --- a/packages/google-cloud-lustre/google/cloud/lustre_v1/gapic_metadata.json +++ b/packages/google-cloud-lustre/google/cloud/lustre_v1/gapic_metadata.json @@ -10,120 +10,270 @@ "grpc": { "libraryClient": "LustreClient", "rpcs": { + "CreateDirectoryPolicy": { + "methods": [ + "create_directory_policy" + ] + }, "CreateInstance": { "methods": [ "create_instance" ] }, + "CreateMirror": { + "methods": [ + "create_mirror" + ] + }, + "DeleteDirectoryPolicy": { + "methods": [ + "delete_directory_policy" + ] + }, "DeleteInstance": { "methods": [ "delete_instance" ] }, + "DeleteMirror": { + "methods": [ + "delete_mirror" + ] + }, "ExportData": { "methods": [ "export_data" ] }, + "GetDirectoryPolicy": { + "methods": [ + "get_directory_policy" + ] + }, "GetInstance": { "methods": [ "get_instance" ] }, + "GetMirror": { + "methods": [ + "get_mirror" + ] + }, "ImportData": { "methods": [ "import_data" ] }, + "ListDirectoryPolicies": { + "methods": [ + "list_directory_policies" + ] + }, "ListInstances": { "methods": [ "list_instances" ] }, + "ListMirrors": { + "methods": [ + "list_mirrors" + ] + }, + "RescheduleMaintenance": { + "methods": [ + "reschedule_maintenance" + ] + }, "UpdateInstance": { "methods": [ "update_instance" ] + }, + "UpdateMirror": { + "methods": [ + "update_mirror" + ] } } }, "grpc-async": { "libraryClient": "LustreAsyncClient", "rpcs": { + "CreateDirectoryPolicy": { + "methods": [ + "create_directory_policy" + ] + }, "CreateInstance": { "methods": [ "create_instance" ] }, + "CreateMirror": { + "methods": [ + "create_mirror" + ] + }, + "DeleteDirectoryPolicy": { + "methods": [ + "delete_directory_policy" + ] + }, "DeleteInstance": { "methods": [ "delete_instance" ] }, + "DeleteMirror": { + "methods": [ + "delete_mirror" + ] + }, "ExportData": { "methods": [ "export_data" ] }, + "GetDirectoryPolicy": { + "methods": [ + "get_directory_policy" + ] + }, "GetInstance": { "methods": [ "get_instance" ] }, + "GetMirror": { + "methods": [ + "get_mirror" + ] + }, "ImportData": { "methods": [ "import_data" ] }, + "ListDirectoryPolicies": { + "methods": [ + "list_directory_policies" + ] + }, "ListInstances": { "methods": [ "list_instances" ] }, + "ListMirrors": { + "methods": [ + "list_mirrors" + ] + }, + "RescheduleMaintenance": { + "methods": [ + "reschedule_maintenance" + ] + }, "UpdateInstance": { "methods": [ "update_instance" ] + }, + "UpdateMirror": { + "methods": [ + "update_mirror" + ] } } }, "rest": { "libraryClient": "LustreClient", "rpcs": { + "CreateDirectoryPolicy": { + "methods": [ + "create_directory_policy" + ] + }, "CreateInstance": { "methods": [ "create_instance" ] }, + "CreateMirror": { + "methods": [ + "create_mirror" + ] + }, + "DeleteDirectoryPolicy": { + "methods": [ + "delete_directory_policy" + ] + }, "DeleteInstance": { "methods": [ "delete_instance" ] }, + "DeleteMirror": { + "methods": [ + "delete_mirror" + ] + }, "ExportData": { "methods": [ "export_data" ] }, + "GetDirectoryPolicy": { + "methods": [ + "get_directory_policy" + ] + }, "GetInstance": { "methods": [ "get_instance" ] }, + "GetMirror": { + "methods": [ + "get_mirror" + ] + }, "ImportData": { "methods": [ "import_data" ] }, + "ListDirectoryPolicies": { + "methods": [ + "list_directory_policies" + ] + }, "ListInstances": { "methods": [ "list_instances" ] }, + "ListMirrors": { + "methods": [ + "list_mirrors" + ] + }, + "RescheduleMaintenance": { + "methods": [ + "reschedule_maintenance" + ] + }, "UpdateInstance": { "methods": [ "update_instance" ] + }, + "UpdateMirror": { + "methods": [ + "update_mirror" + ] } } } diff --git a/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/async_client.py b/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/async_client.py index 8811b8057f5e..35d37e78623a 100644 --- a/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/async_client.py +++ b/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/async_client.py @@ -50,11 +50,17 @@ import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.longrunning import operations_pb2 # type: ignore from google.cloud.lustre_v1.services.lustre import pagers -from google.cloud.lustre_v1.types import instance, transfer +from google.cloud.lustre_v1.types import directory_policy, instance, mirror, transfer +from google.cloud.lustre_v1.types import directory_policy as gcl_directory_policy from google.cloud.lustre_v1.types import instance as gcl_instance +from google.cloud.lustre_v1.types import mirror as gcl_mirror from .client import LustreClient from .transports.base import DEFAULT_CLIENT_INFO, LustreTransport @@ -82,10 +88,18 @@ class LustreAsyncClient: _DEFAULT_ENDPOINT_TEMPLATE = LustreClient._DEFAULT_ENDPOINT_TEMPLATE _DEFAULT_UNIVERSE = LustreClient._DEFAULT_UNIVERSE + crypto_key_path = staticmethod(LustreClient.crypto_key_path) + parse_crypto_key_path = staticmethod(LustreClient.parse_crypto_key_path) + directory_policy_path = staticmethod(LustreClient.directory_policy_path) + parse_directory_policy_path = staticmethod(LustreClient.parse_directory_policy_path) instance_path = staticmethod(LustreClient.instance_path) parse_instance_path = staticmethod(LustreClient.parse_instance_path) + mirror_path = staticmethod(LustreClient.mirror_path) + parse_mirror_path = staticmethod(LustreClient.parse_mirror_path) network_path = staticmethod(LustreClient.network_path) parse_network_path = staticmethod(LustreClient.parse_network_path) + resource_policy_path = staticmethod(LustreClient.resource_policy_path) + parse_resource_policy_path = staticmethod(LustreClient.parse_resource_policy_path) service_account_path = staticmethod(LustreClient.service_account_path) parse_service_account_path = staticmethod(LustreClient.parse_service_account_path) common_billing_account_path = staticmethod(LustreClient.common_billing_account_path) @@ -568,7 +582,6 @@ async def sample_create_instance(): instance.filesystem = "filesystem_value" instance.capacity_gib = 1247 instance.network = "network_value" - instance.per_unit_storage_throughput = 2931 request = lustre_v1.CreateInstanceRequest( parent="parent_value", @@ -725,7 +738,6 @@ async def sample_update_instance(): instance.filesystem = "filesystem_value" instance.capacity_gib = 1247 instance.network = "network_value" - instance.per_unit_storage_throughput = 2931 request = lustre_v1.UpdateInstanceRequest( instance=instance, @@ -975,6 +987,149 @@ async def sample_delete_instance(): # Done; return the response. return response + async def reschedule_maintenance( + self, + request: Optional[Union[instance.RescheduleMaintenanceRequest, dict]] = None, + *, + name: Optional[str] = None, + reschedule: Optional[instance.RescheduleMaintenanceRequest.Reschedule] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Reschedules a planned maintenance event for a + specific instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + async def sample_reschedule_maintenance(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + reschedule = lustre_v1.Reschedule() + reschedule.reschedule_type = "BY_TIME" + + request = lustre_v1.RescheduleMaintenanceRequest( + name="name_value", + reschedule=reschedule, + ) + + # Make the request + operation = await client.reschedule_maintenance(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.lustre_v1.types.RescheduleMaintenanceRequest, dict]]): + The request object. Message for requesting to reschedule + a maintenance event for a specific + instance. + name (:class:`str`): + Required. Format: + + projects/{project}/locations/{location}/instances/{instance} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reschedule (:class:`google.cloud.lustre_v1.types.RescheduleMaintenanceRequest.Reschedule`): + Required. The desired reschedule + settings. + + This corresponds to the ``reschedule`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.lustre_v1.types.Instance` A Managed + Lustre instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, reschedule] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, instance.RescheduleMaintenanceRequest): + request = instance.RescheduleMaintenanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if reschedule is not None: + request.reschedule = reschedule + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.reschedule_maintenance + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + instance.Instance, + metadata_type=instance.OperationMetadata, + ) + + # Done; return the response. + return response + async def import_data( self, request: Optional[Union[transfer.ImportDataRequest, dict]] = None, @@ -1212,49 +1367,139 @@ async def sample_export_data(): # Done; return the response. return response - async def list_operations( + async def create_mirror( self, - request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + request: Optional[Union[gcl_mirror.CreateMirrorRequest, dict]] = None, *, + parent: Optional[str] = None, + mirror: Optional[gcl_mirror.Mirror] = None, + mirror_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. + ) -> operation_async.AsyncOperation: + r"""Creates a new mirror in a given instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + async def sample_create_mirror(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + mirror = lustre_v1.Mirror() + mirror.gcs_path.uri = "uri_value" + mirror.direction = "FROM_CLOUD_STORAGE" + + request = lustre_v1.CreateMirrorRequest( + parent="parent_value", + mirror_id="mirror_id_value", + mirror=mirror, + ) + + # Make the request + operation = await client.create_mirror(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. + request (Optional[Union[google.cloud.lustre_v1.types.CreateMirrorRequest, dict]]): + The request object. Request for CreateMirror. + parent (:class:`str`): + Required. Parent instance resource where the mirror will + be created, in the format: + ``projects/{project}/locations/{location}/instances/{instance}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mirror (:class:`google.cloud.lustre_v1.types.Mirror`): + Required. The mirror to create. + This corresponds to the ``mirror`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mirror_id (:class:`str`): + Required. The ID to use for the mirror. + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-63 characters. + - Must end with a number or a letter. + + The ID cannot be changed after the mirror is created. + + This corresponds to the ``mirror_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be sent along with the request as metadata. Normally, each value must be of type `str`, but for metadata keys ending with the suffix `-bin`, the corresponding values must be of type `bytes`. + Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.lustre_v1.types.Mirror` Represents + a Cloud Storage mirror. + """ # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.ListOperationsRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.ListOperationsRequest(**request) - else: - request_pb = request + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, mirror, mirror_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcl_mirror.CreateMirrorRequest): + request = gcl_mirror.CreateMirrorRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if mirror is not None: + request.mirror = mirror + if mirror_id is not None: + request.mirror_id = mirror_id # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_mirror + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -1262,53 +1507,1166 @@ async def list_operations( # Send the request. response = await rpc( - request_pb, + 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, + gcl_mirror.Mirror, + metadata_type=gcl_mirror.CreateMirrorMetadata, + ) + # Done; return the response. return response - async def get_operation( + async def update_mirror( self, - request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + request: Optional[Union[gcl_mirror.UpdateMirrorRequest, dict]] = None, *, + mirror: Optional[gcl_mirror.Mirror] = 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, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - 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 request is None: - request_pb = operations_pb2.GetOperationRequest() - elif isinstance(request, dict): - request_pb = operations_pb2.GetOperationRequest(**request) - else: - request_pb = request + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single mirror. - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + async def sample_update_mirror(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + mirror = lustre_v1.Mirror() + mirror.gcs_path.uri = "uri_value" + mirror.direction = "FROM_CLOUD_STORAGE" + + request = lustre_v1.UpdateMirrorRequest( + mirror=mirror, + ) + + # Make the request + operation = await client.update_mirror(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.lustre_v1.types.UpdateMirrorRequest, dict]]): + The request object. Request for UpdateMirror. + mirror (:class:`google.cloud.lustre_v1.types.Mirror`): + Required. Mirror to update. The mirror's ``name`` field + is used to identify the mirror to update, in the format: + ``projects/{project}/locations/{location}/instances/{instance}/mirrors/{mirror}`` + + This corresponds to the ``mirror`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If no mask is + provided then all fields present in the request are + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.lustre_v1.types.Mirror` Represents + a Cloud Storage mirror. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [mirror, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcl_mirror.UpdateMirrorRequest): + request = gcl_mirror.UpdateMirrorRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if mirror is not None: + request.mirror = mirror + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_mirror + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("mirror.name", request.mirror.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcl_mirror.Mirror, + metadata_type=instance.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_mirror( + self, + request: Optional[Union[mirror.DeleteMirrorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single mirror. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + async def sample_delete_mirror(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + request = lustre_v1.DeleteMirrorRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_mirror(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.lustre_v1.types.DeleteMirrorRequest, dict]]): + The request object. Request for DeleteMirror. + name (:class:`str`): + Required. Name of the mirror to delete, in the format: + ``projects/{project}/locations/{location}/instances/{instance}/mirrors/{mirror}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, mirror.DeleteMirrorRequest): + request = mirror.DeleteMirrorRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_mirror + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=instance.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_mirror( + self, + request: Optional[Union[mirror.GetMirrorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> mirror.Mirror: + r"""Gets details of a single mirror. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + async def sample_get_mirror(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + request = lustre_v1.GetMirrorRequest( + name="name_value", + ) + + # Make the request + response = await client.get_mirror(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.lustre_v1.types.GetMirrorRequest, dict]]): + The request object. Request for GetMirror. + name (:class:`str`): + Required. Name of the mirror to retrieve, in the format: + ``projects/{project}/locations/{location}/instances/{instance}/mirrors/{mirror}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.lustre_v1.types.Mirror: + Represents a Cloud Storage mirror. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, mirror.GetMirrorRequest): + request = mirror.GetMirrorRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_mirror + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_mirrors( + self, + request: Optional[Union[mirror.ListMirrorsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMirrorsAsyncPager: + r"""Gets details of multiple mirrors under a given + instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + async def sample_list_mirrors(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + request = lustre_v1.ListMirrorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mirrors(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.lustre_v1.types.ListMirrorsRequest, dict]]): + The request object. Request for ListMirrors. + parent (:class:`str`): + Required. Parent instance resource where the mirrors + will be listed, in the format: + ``projects/{project}/locations/{location}/instances/{instance}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.lustre_v1.services.lustre.pagers.ListMirrorsAsyncPager: + Response for ListMirrors. + + 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. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, mirror.ListMirrorsRequest): + request = mirror.ListMirrorsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_mirrors + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListMirrorsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_directory_policy( + self, + request: Optional[ + Union[gcl_directory_policy.CreateDirectoryPolicyRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + directory_policy: Optional[gcl_directory_policy.DirectoryPolicy] = None, + directory_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a directory policy resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + async def sample_create_directory_policy(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + directory_policy = lustre_v1.DirectoryPolicy() + directory_policy.directory_path = "directory_path_value" + + request = lustre_v1.CreateDirectoryPolicyRequest( + parent="parent_value", + directory_policy_id="directory_policy_id_value", + directory_policy=directory_policy, + ) + + # Make the request + operation = await client.create_directory_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.lustre_v1.types.CreateDirectoryPolicyRequest, dict]]): + The request object. Request message for + CreateDirectoryPolicy. + parent (:class:`str`): + Required. The parent instance. It must be in the format + of + ``projects/{project}/locations/{location}/instances/{instance}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + directory_policy (:class:`google.cloud.lustre_v1.types.DirectoryPolicy`): + Required. The directory policy to + create. + + This corresponds to the ``directory_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + directory_policy_id (:class:`str`): + Required. The ID for the + DirectoryPolicy to create. + + This corresponds to the ``directory_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.lustre_v1.types.DirectoryPolicy` A + directory policy for a Managed Lustre instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, directory_policy, directory_policy_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcl_directory_policy.CreateDirectoryPolicyRequest): + request = gcl_directory_policy.CreateDirectoryPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if directory_policy is not None: + request.directory_policy = directory_policy + if directory_policy_id is not None: + request.directory_policy_id = directory_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_directory_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcl_directory_policy.DirectoryPolicy, + metadata_type=instance.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_directory_policy( + self, + request: Optional[ + Union[directory_policy.DeleteDirectoryPolicyRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a directory policy resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + async def sample_delete_directory_policy(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + request = lustre_v1.DeleteDirectoryPolicyRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_directory_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.lustre_v1.types.DeleteDirectoryPolicyRequest, dict]]): + The request object. Request message for + DeleteDirectoryPolicy. + name (:class:`str`): + Required. The resource name of the directory policy. + DirectoryPolicy names have the form + ``projects/{project}/locations/{location}/instances/{instance}/directoryPolicies/{id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, directory_policy.DeleteDirectoryPolicyRequest): + request = directory_policy.DeleteDirectoryPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_directory_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=instance.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_directory_policy( + self, + request: Optional[ + Union[directory_policy.GetDirectoryPolicyRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> directory_policy.DirectoryPolicy: + r"""Gets details of a single directory policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + async def sample_get_directory_policy(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + request = lustre_v1.GetDirectoryPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_directory_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.lustre_v1.types.GetDirectoryPolicyRequest, dict]]): + The request object. Request message for + GetDirectoryPolicy. + name (:class:`str`): + Required. The resource name of the directory policy. + DirectoryPolicy names have the form + ``projects/{project}/locations/{location}/instances/{instance}/directoryPolicies/{id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.lustre_v1.types.DirectoryPolicy: + A directory policy for a Managed + Lustre instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, directory_policy.GetDirectoryPolicyRequest): + request = directory_policy.GetDirectoryPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_directory_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_directory_policies( + self, + request: Optional[ + Union[directory_policy.ListDirectoryPoliciesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListDirectoryPoliciesAsyncPager: + r"""Gets details of multiple directory policies under a + given instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + async def sample_list_directory_policies(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + request = lustre_v1.ListDirectoryPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_directory_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.lustre_v1.types.ListDirectoryPoliciesRequest, dict]]): + The request object. Request message for + ListDirectoryPolicies. + parent (:class:`str`): + Required. The parent instance. It must be in the format + of + ``projects/{project}/locations/{location}/instances/{instance}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.lustre_v1.services.lustre.pagers.ListDirectoryPoliciesAsyncPager: + Response message for + ListDirectoryPolicies. + 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. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, directory_policy.ListDirectoryPoliciesRequest): + request = directory_policy.ListDirectoryPoliciesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_directory_policies + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDirectoryPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1449,6 +2807,329 @@ async def cancel_operation( metadata=metadata, ) + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def get_location( self, request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, diff --git a/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/client.py b/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/client.py index a4a091e79383..aaef22c200dc 100644 --- a/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/client.py +++ b/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/client.py @@ -74,11 +74,17 @@ import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.longrunning import operations_pb2 # type: ignore from google.cloud.lustre_v1.services.lustre import pagers -from google.cloud.lustre_v1.types import instance, transfer +from google.cloud.lustre_v1.types import directory_policy, instance, mirror, transfer +from google.cloud.lustre_v1.types import directory_policy as gcl_directory_policy from google.cloud.lustre_v1.types import instance as gcl_instance +from google.cloud.lustre_v1.types import mirror as gcl_mirror from .transports.base import DEFAULT_CLIENT_INFO, LustreTransport from .transports.grpc import LustreGrpcTransport @@ -178,6 +184,54 @@ def transport(self) -> LustreTransport: """ return self._transport + @staticmethod + def crypto_key_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + ) -> str: + """Returns a fully-qualified crypto_key string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + ) + + @staticmethod + def parse_crypto_key_path(path: str) -> Dict[str, str]: + """Parses a crypto_key path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def directory_policy_path( + project: str, + location: str, + instance: str, + directory_policy: str, + ) -> str: + """Returns a fully-qualified directory_policy string.""" + return "projects/{project}/locations/{location}/instances/{instance}/directoryPolicies/{directory_policy}".format( + project=project, + location=location, + instance=instance, + directory_policy=directory_policy, + ) + + @staticmethod + def parse_directory_policy_path(path: str) -> Dict[str, str]: + """Parses a directory_policy path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/directoryPolicies/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def instance_path( project: str, @@ -200,6 +254,30 @@ def parse_instance_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def mirror_path( + project: str, + location: str, + instance: str, + mirror: str, + ) -> str: + """Returns a fully-qualified mirror string.""" + return "projects/{project}/locations/{location}/instances/{instance}/mirrors/{mirror}".format( + project=project, + location=location, + instance=instance, + mirror=mirror, + ) + + @staticmethod + def parse_mirror_path(path: str) -> Dict[str, str]: + """Parses a mirror path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/mirrors/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def network_path( project: str, @@ -219,6 +297,28 @@ def parse_network_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def resource_policy_path( + project: str, + region: str, + resource_policy: str, + ) -> str: + """Returns a fully-qualified resource_policy string.""" + return "projects/{project}/regions/{region}/resourcePolicies/{resource_policy}".format( + project=project, + region=region, + resource_policy=resource_policy, + ) + + @staticmethod + def parse_resource_policy_path(path: str) -> Dict[str, str]: + """Parses a resource_policy path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/regions/(?P.+?)/resourcePolicies/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def service_account_path( project: str, @@ -904,7 +1004,6 @@ def sample_create_instance(): instance.filesystem = "filesystem_value" instance.capacity_gib = 1247 instance.network = "network_value" - instance.per_unit_storage_throughput = 2931 request = lustre_v1.CreateInstanceRequest( parent="parent_value", @@ -1058,7 +1157,6 @@ def sample_update_instance(): instance.filesystem = "filesystem_value" instance.capacity_gib = 1247 instance.network = "network_value" - instance.per_unit_storage_throughput = 2931 request = lustre_v1.UpdateInstanceRequest( instance=instance, @@ -1302,6 +1400,146 @@ def sample_delete_instance(): # Done; return the response. return response + def reschedule_maintenance( + self, + request: Optional[Union[instance.RescheduleMaintenanceRequest, dict]] = None, + *, + name: Optional[str] = None, + reschedule: Optional[instance.RescheduleMaintenanceRequest.Reschedule] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Reschedules a planned maintenance event for a + specific instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + def sample_reschedule_maintenance(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + reschedule = lustre_v1.Reschedule() + reschedule.reschedule_type = "BY_TIME" + + request = lustre_v1.RescheduleMaintenanceRequest( + name="name_value", + reschedule=reschedule, + ) + + # Make the request + operation = client.reschedule_maintenance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.lustre_v1.types.RescheduleMaintenanceRequest, dict]): + The request object. Message for requesting to reschedule + a maintenance event for a specific + instance. + name (str): + Required. Format: + + projects/{project}/locations/{location}/instances/{instance} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reschedule (google.cloud.lustre_v1.types.RescheduleMaintenanceRequest.Reschedule): + Required. The desired reschedule + settings. + + This corresponds to the ``reschedule`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.lustre_v1.types.Instance` A Managed + Lustre instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, reschedule] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, instance.RescheduleMaintenanceRequest): + request = instance.RescheduleMaintenanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if reschedule is not None: + request.reschedule = reschedule + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.reschedule_maintenance] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + instance.Instance, + metadata_type=instance.OperationMetadata, + ) + + # Done; return the response. + return response + def import_data( self, request: Optional[Union[transfer.ImportDataRequest, dict]] = None, @@ -1534,50 +1772,1226 @@ def sample_export_data(): # Done; return the response. return response - def __enter__(self) -> "LustreClient": - 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( + def create_mirror( self, - request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + request: Optional[Union[gcl_mirror.CreateMirrorRequest, dict]] = None, *, + parent: Optional[str] = None, + mirror: Optional[gcl_mirror.Mirror] = None, + mirror_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. + ) -> operation.Operation: + r"""Creates a new mirror in a given instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + def sample_create_mirror(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + mirror = lustre_v1.Mirror() + mirror.gcs_path.uri = "uri_value" + mirror.direction = "FROM_CLOUD_STORAGE" + + request = lustre_v1.CreateMirrorRequest( + parent="parent_value", + mirror_id="mirror_id_value", + mirror=mirror, + ) + + # Make the request + operation = client.create_mirror(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) 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. + request (Union[google.cloud.lustre_v1.types.CreateMirrorRequest, dict]): + The request object. Request for CreateMirror. + parent (str): + Required. Parent instance resource where the mirror will + be created, in the format: + ``projects/{project}/locations/{location}/instances/{instance}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mirror (google.cloud.lustre_v1.types.Mirror): + Required. The mirror to create. + This corresponds to the ``mirror`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mirror_id (str): + Required. The ID to use for the mirror. + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-63 characters. + - Must end with a number or a letter. + + The ID cannot be changed after the mirror is created. + + This corresponds to the ``mirror_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, Union[str, bytes]]]): Key/value pairs which should be sent along with the request as metadata. Normally, each value must be of type `str`, but for metadata keys ending with the suffix `-bin`, the corresponding values must be of type `bytes`. + Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.lustre_v1.types.Mirror` Represents + a Cloud Storage mirror. + """ # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if request is None: - request_pb = operations_pb2.ListOperationsRequest() - elif isinstance(request, dict): + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, mirror, mirror_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcl_mirror.CreateMirrorRequest): + request = gcl_mirror.CreateMirrorRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if mirror is not None: + request.mirror = mirror + if mirror_id is not None: + request.mirror_id = mirror_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_mirror] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcl_mirror.Mirror, + metadata_type=gcl_mirror.CreateMirrorMetadata, + ) + + # Done; return the response. + return response + + def update_mirror( + self, + request: Optional[Union[gcl_mirror.UpdateMirrorRequest, dict]] = None, + *, + mirror: Optional[gcl_mirror.Mirror] = 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, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single mirror. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + def sample_update_mirror(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + mirror = lustre_v1.Mirror() + mirror.gcs_path.uri = "uri_value" + mirror.direction = "FROM_CLOUD_STORAGE" + + request = lustre_v1.UpdateMirrorRequest( + mirror=mirror, + ) + + # Make the request + operation = client.update_mirror(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.lustre_v1.types.UpdateMirrorRequest, dict]): + The request object. Request for UpdateMirror. + mirror (google.cloud.lustre_v1.types.Mirror): + Required. Mirror to update. The mirror's ``name`` field + is used to identify the mirror to update, in the format: + ``projects/{project}/locations/{location}/instances/{instance}/mirrors/{mirror}`` + + This corresponds to the ``mirror`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If no mask is + provided then all fields present in the request are + overwritten. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.lustre_v1.types.Mirror` Represents + a Cloud Storage mirror. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [mirror, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcl_mirror.UpdateMirrorRequest): + request = gcl_mirror.UpdateMirrorRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if mirror is not None: + request.mirror = mirror + 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_mirror] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("mirror.name", request.mirror.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcl_mirror.Mirror, + metadata_type=instance.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_mirror( + self, + request: Optional[Union[mirror.DeleteMirrorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a single mirror. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + def sample_delete_mirror(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + request = lustre_v1.DeleteMirrorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_mirror(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.lustre_v1.types.DeleteMirrorRequest, dict]): + The request object. Request for DeleteMirror. + name (str): + Required. Name of the mirror to delete, in the format: + ``projects/{project}/locations/{location}/instances/{instance}/mirrors/{mirror}`` + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, mirror.DeleteMirrorRequest): + request = mirror.DeleteMirrorRequest(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_mirror] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=instance.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_mirror( + self, + request: Optional[Union[mirror.GetMirrorRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> mirror.Mirror: + r"""Gets details of a single mirror. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + def sample_get_mirror(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + request = lustre_v1.GetMirrorRequest( + name="name_value", + ) + + # Make the request + response = client.get_mirror(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.lustre_v1.types.GetMirrorRequest, dict]): + The request object. Request for GetMirror. + name (str): + Required. Name of the mirror to retrieve, in the format: + ``projects/{project}/locations/{location}/instances/{instance}/mirrors/{mirror}`` + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.lustre_v1.types.Mirror: + Represents a Cloud Storage mirror. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, mirror.GetMirrorRequest): + request = mirror.GetMirrorRequest(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_mirror] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_mirrors( + self, + request: Optional[Union[mirror.ListMirrorsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMirrorsPager: + r"""Gets details of multiple mirrors under a given + instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + def sample_list_mirrors(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + request = lustre_v1.ListMirrorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mirrors(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.lustre_v1.types.ListMirrorsRequest, dict]): + The request object. Request for ListMirrors. + parent (str): + Required. Parent instance resource where the mirrors + will be listed, in the format: + ``projects/{project}/locations/{location}/instances/{instance}`` + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.lustre_v1.services.lustre.pagers.ListMirrorsPager: + Response for ListMirrors. + + 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. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, mirror.ListMirrorsRequest): + request = mirror.ListMirrorsRequest(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_mirrors] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListMirrorsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_directory_policy( + self, + request: Optional[ + Union[gcl_directory_policy.CreateDirectoryPolicyRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + directory_policy: Optional[gcl_directory_policy.DirectoryPolicy] = None, + directory_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a directory policy resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + def sample_create_directory_policy(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + directory_policy = lustre_v1.DirectoryPolicy() + directory_policy.directory_path = "directory_path_value" + + request = lustre_v1.CreateDirectoryPolicyRequest( + parent="parent_value", + directory_policy_id="directory_policy_id_value", + directory_policy=directory_policy, + ) + + # Make the request + operation = client.create_directory_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.lustre_v1.types.CreateDirectoryPolicyRequest, dict]): + The request object. Request message for + CreateDirectoryPolicy. + parent (str): + Required. The parent instance. It must be in the format + of + ``projects/{project}/locations/{location}/instances/{instance}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + directory_policy (google.cloud.lustre_v1.types.DirectoryPolicy): + Required. The directory policy to + create. + + This corresponds to the ``directory_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + directory_policy_id (str): + Required. The ID for the + DirectoryPolicy to create. + + This corresponds to the ``directory_policy_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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.lustre_v1.types.DirectoryPolicy` A + directory policy for a Managed Lustre instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, directory_policy, directory_policy_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcl_directory_policy.CreateDirectoryPolicyRequest): + request = gcl_directory_policy.CreateDirectoryPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if directory_policy is not None: + request.directory_policy = directory_policy + if directory_policy_id is not None: + request.directory_policy_id = directory_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_directory_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcl_directory_policy.DirectoryPolicy, + metadata_type=instance.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_directory_policy( + self, + request: Optional[ + Union[directory_policy.DeleteDirectoryPolicyRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a directory policy resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + def sample_delete_directory_policy(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + request = lustre_v1.DeleteDirectoryPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_directory_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.lustre_v1.types.DeleteDirectoryPolicyRequest, dict]): + The request object. Request message for + DeleteDirectoryPolicy. + name (str): + Required. The resource name of the directory policy. + DirectoryPolicy names have the form + ``projects/{project}/locations/{location}/instances/{instance}/directoryPolicies/{id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, directory_policy.DeleteDirectoryPolicyRequest): + request = directory_policy.DeleteDirectoryPolicyRequest(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_directory_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=instance.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_directory_policy( + self, + request: Optional[ + Union[directory_policy.GetDirectoryPolicyRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> directory_policy.DirectoryPolicy: + r"""Gets details of a single directory policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + def sample_get_directory_policy(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + request = lustre_v1.GetDirectoryPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_directory_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.lustre_v1.types.GetDirectoryPolicyRequest, dict]): + The request object. Request message for + GetDirectoryPolicy. + name (str): + Required. The resource name of the directory policy. + DirectoryPolicy names have the form + ``projects/{project}/locations/{location}/instances/{instance}/directoryPolicies/{id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.lustre_v1.types.DirectoryPolicy: + A directory policy for a Managed + Lustre instance. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, directory_policy.GetDirectoryPolicyRequest): + request = directory_policy.GetDirectoryPolicyRequest(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_directory_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_directory_policies( + self, + request: Optional[ + Union[directory_policy.ListDirectoryPoliciesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListDirectoryPoliciesPager: + r"""Gets details of multiple directory policies under a + given instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import lustre_v1 + + def sample_list_directory_policies(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + request = lustre_v1.ListDirectoryPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_directory_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.lustre_v1.types.ListDirectoryPoliciesRequest, dict]): + The request object. Request message for + ListDirectoryPolicies. + parent (str): + Required. The parent instance. It must be in the format + of + ``projects/{project}/locations/{location}/instances/{instance}``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.lustre_v1.services.lustre.pagers.ListDirectoryPoliciesPager: + Response message for + ListDirectoryPolicies. + 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. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, directory_policy.ListDirectoryPoliciesRequest): + request = directory_policy.ListDirectoryPoliciesRequest(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_directory_policies] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDirectoryPoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "LustreClient": + 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[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): request_pb = operations_pb2.ListOperationsRequest(**request) else: request_pb = request @@ -1792,6 +3206,339 @@ def cancel_operation( metadata=metadata, ) + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + def get_location( self, request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, diff --git a/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/pagers.py b/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/pagers.py index b322c4fcaa11..982efd4e6006 100644 --- a/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/pagers.py +++ b/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/pagers.py @@ -38,7 +38,7 @@ OptionalRetry = Union[retries.Retry, object, None] # type: ignore OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore -from google.cloud.lustre_v1.types import instance +from google.cloud.lustre_v1.types import directory_policy, instance, mirror class ListInstancesPager: @@ -195,3 +195,319 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMirrorsPager: + """A pager for iterating through ``list_mirrors`` requests. + + This class thinly wraps an initial + :class:`google.cloud.lustre_v1.types.ListMirrorsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``mirrors`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMirrors`` requests and continue to iterate + through the ``mirrors`` field on the + corresponding responses. + + All the usual :class:`google.cloud.lustre_v1.types.ListMirrorsResponse` + 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[..., mirror.ListMirrorsResponse], + request: mirror.ListMirrorsRequest, + response: mirror.ListMirrorsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.lustre_v1.types.ListMirrorsRequest): + The initial request object. + response (google.cloud.lustre_v1.types.ListMirrorsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = mirror.ListMirrorsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[mirror.ListMirrorsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[mirror.Mirror]: + for page in self.pages: + yield from page.mirrors + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMirrorsAsyncPager: + """A pager for iterating through ``list_mirrors`` requests. + + This class thinly wraps an initial + :class:`google.cloud.lustre_v1.types.ListMirrorsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``mirrors`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMirrors`` requests and continue to iterate + through the ``mirrors`` field on the + corresponding responses. + + All the usual :class:`google.cloud.lustre_v1.types.ListMirrorsResponse` + 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[mirror.ListMirrorsResponse]], + request: mirror.ListMirrorsRequest, + response: mirror.ListMirrorsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.lustre_v1.types.ListMirrorsRequest): + The initial request object. + response (google.cloud.lustre_v1.types.ListMirrorsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = mirror.ListMirrorsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[mirror.ListMirrorsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[mirror.Mirror]: + async def async_generator(): + async for page in self.pages: + for response in page.mirrors: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListDirectoryPoliciesPager: + """A pager for iterating through ``list_directory_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.lustre_v1.types.ListDirectoryPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``directory_policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDirectoryPolicies`` requests and continue to iterate + through the ``directory_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.lustre_v1.types.ListDirectoryPoliciesResponse` + 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[..., directory_policy.ListDirectoryPoliciesResponse], + request: directory_policy.ListDirectoryPoliciesRequest, + response: directory_policy.ListDirectoryPoliciesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.lustre_v1.types.ListDirectoryPoliciesRequest): + The initial request object. + response (google.cloud.lustre_v1.types.ListDirectoryPoliciesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = directory_policy.ListDirectoryPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[directory_policy.ListDirectoryPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[directory_policy.DirectoryPolicy]: + for page in self.pages: + yield from page.directory_policies + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListDirectoryPoliciesAsyncPager: + """A pager for iterating through ``list_directory_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.lustre_v1.types.ListDirectoryPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``directory_policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDirectoryPolicies`` requests and continue to iterate + through the ``directory_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.lustre_v1.types.ListDirectoryPoliciesResponse` + 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[directory_policy.ListDirectoryPoliciesResponse] + ], + request: directory_policy.ListDirectoryPoliciesRequest, + response: directory_policy.ListDirectoryPoliciesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.lustre_v1.types.ListDirectoryPoliciesRequest): + The initial request object. + response (google.cloud.lustre_v1.types.ListDirectoryPoliciesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = directory_policy.ListDirectoryPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[directory_policy.ListDirectoryPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[directory_policy.DirectoryPolicy]: + async def async_generator(): + async for page in self.pages: + for response in page.directory_policies: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/base.py b/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/base.py index d16c909afafe..c2efb148df18 100644 --- a/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/base.py +++ b/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/base.py @@ -24,12 +24,18 @@ from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.lustre_v1 import gapic_version as package_version -from google.cloud.lustre_v1.types import instance, transfer +from google.cloud.lustre_v1.types import directory_policy, instance, mirror, transfer +from google.cloud.lustre_v1.types import directory_policy as gcl_directory_policy from google.cloud.lustre_v1.types import instance as gcl_instance +from google.cloud.lustre_v1.types import mirror as gcl_mirror DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ @@ -168,6 +174,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.reschedule_maintenance: gapic_v1.method.wrap_method( + self.reschedule_maintenance, + default_timeout=None, + client_info=client_info, + ), self.import_data: gapic_v1.method.wrap_method( self.import_data, default_timeout=None, @@ -178,6 +189,51 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.create_mirror: gapic_v1.method.wrap_method( + self.create_mirror, + default_timeout=None, + client_info=client_info, + ), + self.update_mirror: gapic_v1.method.wrap_method( + self.update_mirror, + default_timeout=None, + client_info=client_info, + ), + self.delete_mirror: gapic_v1.method.wrap_method( + self.delete_mirror, + default_timeout=None, + client_info=client_info, + ), + self.get_mirror: gapic_v1.method.wrap_method( + self.get_mirror, + default_timeout=None, + client_info=client_info, + ), + self.list_mirrors: gapic_v1.method.wrap_method( + self.list_mirrors, + default_timeout=None, + client_info=client_info, + ), + self.create_directory_policy: gapic_v1.method.wrap_method( + self.create_directory_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_directory_policy: gapic_v1.method.wrap_method( + self.delete_directory_policy, + default_timeout=None, + client_info=client_info, + ), + self.get_directory_policy: gapic_v1.method.wrap_method( + self.get_directory_policy, + default_timeout=None, + client_info=client_info, + ), + self.list_directory_policies: gapic_v1.method.wrap_method( + self.list_directory_policies, + default_timeout=None, + client_info=client_info, + ), self.get_location: gapic_v1.method.wrap_method( self.get_location, default_timeout=None, @@ -188,6 +244,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), self.cancel_operation: gapic_v1.method.wrap_method( self.cancel_operation, default_timeout=None, @@ -271,6 +342,15 @@ def delete_instance( ]: raise NotImplementedError() + @property + def reschedule_maintenance( + self, + ) -> Callable[ + [instance.RescheduleMaintenanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def import_data( self, @@ -289,6 +369,92 @@ def export_data( ]: raise NotImplementedError() + @property + def create_mirror( + self, + ) -> Callable[ + [gcl_mirror.CreateMirrorRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_mirror( + self, + ) -> Callable[ + [gcl_mirror.UpdateMirrorRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_mirror( + self, + ) -> Callable[ + [mirror.DeleteMirrorRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_mirror( + self, + ) -> Callable[ + [mirror.GetMirrorRequest], Union[mirror.Mirror, Awaitable[mirror.Mirror]] + ]: + raise NotImplementedError() + + @property + def list_mirrors( + self, + ) -> Callable[ + [mirror.ListMirrorsRequest], + Union[mirror.ListMirrorsResponse, Awaitable[mirror.ListMirrorsResponse]], + ]: + raise NotImplementedError() + + @property + def create_directory_policy( + self, + ) -> Callable[ + [gcl_directory_policy.CreateDirectoryPolicyRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_directory_policy( + self, + ) -> Callable[ + [directory_policy.DeleteDirectoryPolicyRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_directory_policy( + self, + ) -> Callable[ + [directory_policy.GetDirectoryPolicyRequest], + Union[ + directory_policy.DirectoryPolicy, + Awaitable[directory_policy.DirectoryPolicy], + ], + ]: + raise NotImplementedError() + + @property + def list_directory_policies( + self, + ) -> Callable[ + [directory_policy.ListDirectoryPoliciesRequest], + Union[ + directory_policy.ListDirectoryPoliciesResponse, + Awaitable[directory_policy.ListDirectoryPoliciesResponse], + ], + ]: + raise NotImplementedError() + @property def list_operations( self, @@ -328,6 +494,36 @@ def delete_operation( ]: 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 get_location( self, diff --git a/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/grpc.py b/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/grpc.py index 6b698e2adad8..f7a732a9857a 100644 --- a/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/grpc.py +++ b/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/grpc.py @@ -27,11 +27,17 @@ from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson -from google.cloud.lustre_v1.types import instance, transfer +from google.cloud.lustre_v1.types import directory_policy, instance, mirror, transfer +from google.cloud.lustre_v1.types import directory_policy as gcl_directory_policy from google.cloud.lustre_v1.types import instance as gcl_instance +from google.cloud.lustre_v1.types import mirror as gcl_mirror from .base import DEFAULT_CLIENT_INFO, LustreTransport @@ -476,6 +482,33 @@ def delete_instance( ) return self._stubs["delete_instance"] + @property + def reschedule_maintenance( + self, + ) -> Callable[[instance.RescheduleMaintenanceRequest], operations_pb2.Operation]: + r"""Return a callable for the reschedule maintenance method over gRPC. + + Reschedules a planned maintenance event for a + specific instance. + + Returns: + Callable[[~.RescheduleMaintenanceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "reschedule_maintenance" not in self._stubs: + self._stubs["reschedule_maintenance"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/RescheduleMaintenance", + request_serializer=instance.RescheduleMaintenanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["reschedule_maintenance"] + @property def import_data( self, @@ -530,6 +563,249 @@ def export_data( ) return self._stubs["export_data"] + @property + def create_mirror( + self, + ) -> Callable[[gcl_mirror.CreateMirrorRequest], operations_pb2.Operation]: + r"""Return a callable for the create mirror method over gRPC. + + Creates a new mirror in a given instance. + + Returns: + Callable[[~.CreateMirrorRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mirror" not in self._stubs: + self._stubs["create_mirror"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/CreateMirror", + request_serializer=gcl_mirror.CreateMirrorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_mirror"] + + @property + def update_mirror( + self, + ) -> Callable[[gcl_mirror.UpdateMirrorRequest], operations_pb2.Operation]: + r"""Return a callable for the update mirror method over gRPC. + + Updates the parameters of a single mirror. + + Returns: + Callable[[~.UpdateMirrorRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mirror" not in self._stubs: + self._stubs["update_mirror"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/UpdateMirror", + request_serializer=gcl_mirror.UpdateMirrorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_mirror"] + + @property + def delete_mirror( + self, + ) -> Callable[[mirror.DeleteMirrorRequest], operations_pb2.Operation]: + r"""Return a callable for the delete mirror method over gRPC. + + Deletes a single mirror. + + Returns: + Callable[[~.DeleteMirrorRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mirror" not in self._stubs: + self._stubs["delete_mirror"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/DeleteMirror", + request_serializer=mirror.DeleteMirrorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_mirror"] + + @property + def get_mirror(self) -> Callable[[mirror.GetMirrorRequest], mirror.Mirror]: + r"""Return a callable for the get mirror method over gRPC. + + Gets details of a single mirror. + + Returns: + Callable[[~.GetMirrorRequest], + ~.Mirror]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mirror" not in self._stubs: + self._stubs["get_mirror"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/GetMirror", + request_serializer=mirror.GetMirrorRequest.serialize, + response_deserializer=mirror.Mirror.deserialize, + ) + return self._stubs["get_mirror"] + + @property + def list_mirrors( + self, + ) -> Callable[[mirror.ListMirrorsRequest], mirror.ListMirrorsResponse]: + r"""Return a callable for the list mirrors method over gRPC. + + Gets details of multiple mirrors under a given + instance. + + Returns: + Callable[[~.ListMirrorsRequest], + ~.ListMirrorsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mirrors" not in self._stubs: + self._stubs["list_mirrors"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/ListMirrors", + request_serializer=mirror.ListMirrorsRequest.serialize, + response_deserializer=mirror.ListMirrorsResponse.deserialize, + ) + return self._stubs["list_mirrors"] + + @property + def create_directory_policy( + self, + ) -> Callable[ + [gcl_directory_policy.CreateDirectoryPolicyRequest], operations_pb2.Operation + ]: + r"""Return a callable for the create directory policy method over gRPC. + + Creates a directory policy resource. + + Returns: + Callable[[~.CreateDirectoryPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_directory_policy" not in self._stubs: + self._stubs["create_directory_policy"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/CreateDirectoryPolicy", + request_serializer=gcl_directory_policy.CreateDirectoryPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_directory_policy"] + + @property + def delete_directory_policy( + self, + ) -> Callable[ + [directory_policy.DeleteDirectoryPolicyRequest], operations_pb2.Operation + ]: + r"""Return a callable for the delete directory policy method over gRPC. + + Deletes a directory policy resource. + + Returns: + Callable[[~.DeleteDirectoryPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_directory_policy" not in self._stubs: + self._stubs["delete_directory_policy"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/DeleteDirectoryPolicy", + request_serializer=directory_policy.DeleteDirectoryPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_directory_policy"] + + @property + def get_directory_policy( + self, + ) -> Callable[ + [directory_policy.GetDirectoryPolicyRequest], directory_policy.DirectoryPolicy + ]: + r"""Return a callable for the get directory policy method over gRPC. + + Gets details of a single directory policy. + + Returns: + Callable[[~.GetDirectoryPolicyRequest], + ~.DirectoryPolicy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_directory_policy" not in self._stubs: + self._stubs["get_directory_policy"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/GetDirectoryPolicy", + request_serializer=directory_policy.GetDirectoryPolicyRequest.serialize, + response_deserializer=directory_policy.DirectoryPolicy.deserialize, + ) + return self._stubs["get_directory_policy"] + + @property + def list_directory_policies( + self, + ) -> Callable[ + [directory_policy.ListDirectoryPoliciesRequest], + directory_policy.ListDirectoryPoliciesResponse, + ]: + r"""Return a callable for the list directory policies method over gRPC. + + Gets details of multiple directory policies under a + given instance. + + Returns: + Callable[[~.ListDirectoryPoliciesRequest], + ~.ListDirectoryPoliciesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_directory_policies" not in self._stubs: + self._stubs["list_directory_policies"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/ListDirectoryPolicies", + request_serializer=directory_policy.ListDirectoryPoliciesRequest.serialize, + response_deserializer=directory_policy.ListDirectoryPoliciesResponse.deserialize, + ) + return self._stubs["list_directory_policies"] + def close(self): self._logged_channel.close() @@ -639,6 +915,86 @@ def get_location( ) return self._stubs["get_location"] + @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._logged_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._logged_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._logged_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" diff --git a/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/grpc_asyncio.py b/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/grpc_asyncio.py index f210e49c8ef0..d29eefe3e038 100644 --- a/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/grpc_asyncio.py +++ b/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/grpc_asyncio.py @@ -29,12 +29,18 @@ from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson from grpc.experimental import aio # type: ignore -from google.cloud.lustre_v1.types import instance, transfer +from google.cloud.lustre_v1.types import directory_policy, instance, mirror, transfer +from google.cloud.lustre_v1.types import directory_policy as gcl_directory_policy from google.cloud.lustre_v1.types import instance as gcl_instance +from google.cloud.lustre_v1.types import mirror as gcl_mirror from .base import DEFAULT_CLIENT_INFO, LustreTransport from .grpc import LustreGrpcTransport @@ -492,6 +498,35 @@ def delete_instance( ) return self._stubs["delete_instance"] + @property + def reschedule_maintenance( + self, + ) -> Callable[ + [instance.RescheduleMaintenanceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the reschedule maintenance method over gRPC. + + Reschedules a planned maintenance event for a + specific instance. + + Returns: + Callable[[~.RescheduleMaintenanceRequest], + 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 "reschedule_maintenance" not in self._stubs: + self._stubs["reschedule_maintenance"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/RescheduleMaintenance", + request_serializer=instance.RescheduleMaintenanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["reschedule_maintenance"] + @property def import_data( self, @@ -546,6 +581,258 @@ def export_data( ) return self._stubs["export_data"] + @property + def create_mirror( + self, + ) -> Callable[ + [gcl_mirror.CreateMirrorRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create mirror method over gRPC. + + Creates a new mirror in a given instance. + + Returns: + Callable[[~.CreateMirrorRequest], + 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_mirror" not in self._stubs: + self._stubs["create_mirror"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/CreateMirror", + request_serializer=gcl_mirror.CreateMirrorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_mirror"] + + @property + def update_mirror( + self, + ) -> Callable[ + [gcl_mirror.UpdateMirrorRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update mirror method over gRPC. + + Updates the parameters of a single mirror. + + Returns: + Callable[[~.UpdateMirrorRequest], + 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_mirror" not in self._stubs: + self._stubs["update_mirror"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/UpdateMirror", + request_serializer=gcl_mirror.UpdateMirrorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_mirror"] + + @property + def delete_mirror( + self, + ) -> Callable[[mirror.DeleteMirrorRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete mirror method over gRPC. + + Deletes a single mirror. + + Returns: + Callable[[~.DeleteMirrorRequest], + 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_mirror" not in self._stubs: + self._stubs["delete_mirror"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/DeleteMirror", + request_serializer=mirror.DeleteMirrorRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_mirror"] + + @property + def get_mirror( + self, + ) -> Callable[[mirror.GetMirrorRequest], Awaitable[mirror.Mirror]]: + r"""Return a callable for the get mirror method over gRPC. + + Gets details of a single mirror. + + Returns: + Callable[[~.GetMirrorRequest], + Awaitable[~.Mirror]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mirror" not in self._stubs: + self._stubs["get_mirror"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/GetMirror", + request_serializer=mirror.GetMirrorRequest.serialize, + response_deserializer=mirror.Mirror.deserialize, + ) + return self._stubs["get_mirror"] + + @property + def list_mirrors( + self, + ) -> Callable[[mirror.ListMirrorsRequest], Awaitable[mirror.ListMirrorsResponse]]: + r"""Return a callable for the list mirrors method over gRPC. + + Gets details of multiple mirrors under a given + instance. + + Returns: + Callable[[~.ListMirrorsRequest], + Awaitable[~.ListMirrorsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_mirrors" not in self._stubs: + self._stubs["list_mirrors"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/ListMirrors", + request_serializer=mirror.ListMirrorsRequest.serialize, + response_deserializer=mirror.ListMirrorsResponse.deserialize, + ) + return self._stubs["list_mirrors"] + + @property + def create_directory_policy( + self, + ) -> Callable[ + [gcl_directory_policy.CreateDirectoryPolicyRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create directory policy method over gRPC. + + Creates a directory policy resource. + + Returns: + Callable[[~.CreateDirectoryPolicyRequest], + 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_directory_policy" not in self._stubs: + self._stubs["create_directory_policy"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/CreateDirectoryPolicy", + request_serializer=gcl_directory_policy.CreateDirectoryPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_directory_policy"] + + @property + def delete_directory_policy( + self, + ) -> Callable[ + [directory_policy.DeleteDirectoryPolicyRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete directory policy method over gRPC. + + Deletes a directory policy resource. + + Returns: + Callable[[~.DeleteDirectoryPolicyRequest], + 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_directory_policy" not in self._stubs: + self._stubs["delete_directory_policy"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/DeleteDirectoryPolicy", + request_serializer=directory_policy.DeleteDirectoryPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_directory_policy"] + + @property + def get_directory_policy( + self, + ) -> Callable[ + [directory_policy.GetDirectoryPolicyRequest], + Awaitable[directory_policy.DirectoryPolicy], + ]: + r"""Return a callable for the get directory policy method over gRPC. + + Gets details of a single directory policy. + + Returns: + Callable[[~.GetDirectoryPolicyRequest], + Awaitable[~.DirectoryPolicy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_directory_policy" not in self._stubs: + self._stubs["get_directory_policy"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/GetDirectoryPolicy", + request_serializer=directory_policy.GetDirectoryPolicyRequest.serialize, + response_deserializer=directory_policy.DirectoryPolicy.deserialize, + ) + return self._stubs["get_directory_policy"] + + @property + def list_directory_policies( + self, + ) -> Callable[ + [directory_policy.ListDirectoryPoliciesRequest], + Awaitable[directory_policy.ListDirectoryPoliciesResponse], + ]: + r"""Return a callable for the list directory policies method over gRPC. + + Gets details of multiple directory policies under a + given instance. + + Returns: + Callable[[~.ListDirectoryPoliciesRequest], + Awaitable[~.ListDirectoryPoliciesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_directory_policies" not in self._stubs: + self._stubs["list_directory_policies"] = self._logged_channel.unary_unary( + "/google.cloud.lustre.v1.Lustre/ListDirectoryPolicies", + request_serializer=directory_policy.ListDirectoryPoliciesRequest.serialize, + response_deserializer=directory_policy.ListDirectoryPoliciesResponse.deserialize, + ) + return self._stubs["list_directory_policies"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -574,6 +861,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.reschedule_maintenance: self._wrap_method( + self.reschedule_maintenance, + default_timeout=None, + client_info=client_info, + ), self.import_data: self._wrap_method( self.import_data, default_timeout=None, @@ -584,6 +876,51 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.create_mirror: self._wrap_method( + self.create_mirror, + default_timeout=None, + client_info=client_info, + ), + self.update_mirror: self._wrap_method( + self.update_mirror, + default_timeout=None, + client_info=client_info, + ), + self.delete_mirror: self._wrap_method( + self.delete_mirror, + default_timeout=None, + client_info=client_info, + ), + self.get_mirror: self._wrap_method( + self.get_mirror, + default_timeout=None, + client_info=client_info, + ), + self.list_mirrors: self._wrap_method( + self.list_mirrors, + default_timeout=None, + client_info=client_info, + ), + self.create_directory_policy: self._wrap_method( + self.create_directory_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_directory_policy: self._wrap_method( + self.delete_directory_policy, + default_timeout=None, + client_info=client_info, + ), + self.get_directory_policy: self._wrap_method( + self.get_directory_policy, + default_timeout=None, + client_info=client_info, + ), + self.list_directory_policies: self._wrap_method( + self.list_directory_policies, + default_timeout=None, + client_info=client_info, + ), self.get_location: self._wrap_method( self.get_location, default_timeout=None, @@ -594,6 +931,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), self.cancel_operation: self._wrap_method( self.cancel_operation, default_timeout=None, @@ -734,5 +1086,85 @@ def get_location( ) return self._stubs["get_location"] + @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._logged_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._logged_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._logged_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__ = ("LustreGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/rest.py b/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/rest.py index cee3e083fe44..7f3e47f37b84 100644 --- a/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/rest.py +++ b/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/rest.py @@ -26,13 +26,19 @@ from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.requests import AuthorizedSession # type: ignore from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format from requests import __version__ as requests_version from google.cloud.lustre_v1._compat import transcode_request -from google.cloud.lustre_v1.types import instance, transfer +from google.cloud.lustre_v1.types import directory_policy, instance, mirror, transfer +from google.cloud.lustre_v1.types import directory_policy as gcl_directory_policy from google.cloud.lustre_v1.types import instance as gcl_instance +from google.cloud.lustre_v1.types import mirror as gcl_mirror from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO from .rest_base import _BaseLustreRestTransport @@ -75,6 +81,14 @@ class LustreRestInterceptor: .. code-block:: python class MyCustomLustreInterceptor(LustreRestInterceptor): + def pre_create_directory_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_directory_policy(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_instance(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -83,6 +97,22 @@ def post_create_instance(self, response): logging.log(f"Received response: {response}") return response + def pre_create_mirror(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_mirror(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_directory_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_directory_policy(self, response): + logging.log(f"Received response: {response}") + return response + def pre_delete_instance(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -91,6 +121,14 @@ def post_delete_instance(self, response): logging.log(f"Received response: {response}") return response + def pre_delete_mirror(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_mirror(self, response): + logging.log(f"Received response: {response}") + return response + def pre_export_data(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -99,6 +137,14 @@ def post_export_data(self, response): logging.log(f"Received response: {response}") return response + def pre_get_directory_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_directory_policy(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_instance(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -107,6 +153,14 @@ def post_get_instance(self, response): logging.log(f"Received response: {response}") return response + def pre_get_mirror(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_mirror(self, response): + logging.log(f"Received response: {response}") + return response + def pre_import_data(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -115,6 +169,14 @@ def post_import_data(self, response): logging.log(f"Received response: {response}") return response + def pre_list_directory_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_directory_policies(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_instances(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -123,6 +185,22 @@ def post_list_instances(self, response): logging.log(f"Received response: {response}") return response + def pre_list_mirrors(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_mirrors(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_reschedule_maintenance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_reschedule_maintenance(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_instance(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -131,12 +209,69 @@ def post_update_instance(self, response): logging.log(f"Received response: {response}") return response + def pre_update_mirror(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_mirror(self, response): + logging.log(f"Received response: {response}") + return response + transport = LustreRestTransport(interceptor=MyCustomLustreInterceptor()) client = LustreClient(transport=transport) """ + def pre_create_directory_policy( + self, + request: gcl_directory_policy.CreateDirectoryPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcl_directory_policy.CreateDirectoryPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_directory_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Lustre server. + """ + return request, metadata + + def post_create_directory_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_directory_policy + + DEPRECATED. Please use the `post_create_directory_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Lustre server but before + it is returned to user code. This `post_create_directory_policy` interceptor runs + before the `post_create_directory_policy_with_metadata` interceptor. + """ + return response + + def post_create_directory_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_directory_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Lustre server but before it is returned to user code. + + We recommend only using this `post_create_directory_policy_with_metadata` + interceptor in new development instead of the `post_create_directory_policy` interceptor. + When both interceptors are used, this `post_create_directory_policy_with_metadata` interceptor runs after the + `post_create_directory_policy` interceptor. The (possibly modified) response returned by + `post_create_directory_policy` will be passed to + `post_create_directory_policy_with_metadata`. + """ + return response, metadata + def pre_create_instance( self, request: gcl_instance.CreateInstanceRequest, @@ -185,6 +320,101 @@ def post_create_instance_with_metadata( """ return response, metadata + def pre_create_mirror( + self, + request: gcl_mirror.CreateMirrorRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcl_mirror.CreateMirrorRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_mirror + + Override in a subclass to manipulate the request or metadata + before they are sent to the Lustre server. + """ + return request, metadata + + def post_create_mirror( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_mirror + + DEPRECATED. Please use the `post_create_mirror_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Lustre server but before + it is returned to user code. This `post_create_mirror` interceptor runs + before the `post_create_mirror_with_metadata` interceptor. + """ + return response + + def post_create_mirror_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_mirror + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Lustre server but before it is returned to user code. + + We recommend only using this `post_create_mirror_with_metadata` + interceptor in new development instead of the `post_create_mirror` interceptor. + When both interceptors are used, this `post_create_mirror_with_metadata` interceptor runs after the + `post_create_mirror` interceptor. The (possibly modified) response returned by + `post_create_mirror` will be passed to + `post_create_mirror_with_metadata`. + """ + return response, metadata + + def pre_delete_directory_policy( + self, + request: directory_policy.DeleteDirectoryPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + directory_policy.DeleteDirectoryPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_directory_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Lustre server. + """ + return request, metadata + + def post_delete_directory_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_directory_policy + + DEPRECATED. Please use the `post_delete_directory_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Lustre server but before + it is returned to user code. This `post_delete_directory_policy` interceptor runs + before the `post_delete_directory_policy_with_metadata` interceptor. + """ + return response + + def post_delete_directory_policy_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_directory_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Lustre server but before it is returned to user code. + + We recommend only using this `post_delete_directory_policy_with_metadata` + interceptor in new development instead of the `post_delete_directory_policy` interceptor. + When both interceptors are used, this `post_delete_directory_policy_with_metadata` interceptor runs after the + `post_delete_directory_policy` interceptor. The (possibly modified) response returned by + `post_delete_directory_policy` will be passed to + `post_delete_directory_policy_with_metadata`. + """ + return response, metadata + def pre_delete_instance( self, request: instance.DeleteInstanceRequest, @@ -231,6 +461,52 @@ def post_delete_instance_with_metadata( """ return response, metadata + def pre_delete_mirror( + self, + request: mirror.DeleteMirrorRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[mirror.DeleteMirrorRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_mirror + + Override in a subclass to manipulate the request or metadata + before they are sent to the Lustre server. + """ + return request, metadata + + def post_delete_mirror( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_mirror + + DEPRECATED. Please use the `post_delete_mirror_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Lustre server but before + it is returned to user code. This `post_delete_mirror` interceptor runs + before the `post_delete_mirror_with_metadata` interceptor. + """ + return response + + def post_delete_mirror_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_mirror + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Lustre server but before it is returned to user code. + + We recommend only using this `post_delete_mirror_with_metadata` + interceptor in new development instead of the `post_delete_mirror` interceptor. + When both interceptors are used, this `post_delete_mirror_with_metadata` interceptor runs after the + `post_delete_mirror` interceptor. The (possibly modified) response returned by + `post_delete_mirror` will be passed to + `post_delete_mirror_with_metadata`. + """ + return response, metadata + def pre_export_data( self, request: transfer.ExportDataRequest, @@ -277,6 +553,57 @@ def post_export_data_with_metadata( """ return response, metadata + def pre_get_directory_policy( + self, + request: directory_policy.GetDirectoryPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + directory_policy.GetDirectoryPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_directory_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Lustre server. + """ + return request, metadata + + def post_get_directory_policy( + self, response: directory_policy.DirectoryPolicy + ) -> directory_policy.DirectoryPolicy: + """Post-rpc interceptor for get_directory_policy + + DEPRECATED. Please use the `post_get_directory_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Lustre server but before + it is returned to user code. This `post_get_directory_policy` interceptor runs + before the `post_get_directory_policy_with_metadata` interceptor. + """ + return response + + def post_get_directory_policy_with_metadata( + self, + response: directory_policy.DirectoryPolicy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + directory_policy.DirectoryPolicy, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_directory_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Lustre server but before it is returned to user code. + + We recommend only using this `post_get_directory_policy_with_metadata` + interceptor in new development instead of the `post_get_directory_policy` interceptor. + When both interceptors are used, this `post_get_directory_policy_with_metadata` interceptor runs after the + `post_get_directory_policy` interceptor. The (possibly modified) response returned by + `post_get_directory_policy` will be passed to + `post_get_directory_policy_with_metadata`. + """ + return response, metadata + def pre_get_instance( self, request: instance.GetInstanceRequest, @@ -321,6 +648,48 @@ def post_get_instance_with_metadata( """ return response, metadata + def pre_get_mirror( + self, + request: mirror.GetMirrorRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[mirror.GetMirrorRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_mirror + + Override in a subclass to manipulate the request or metadata + before they are sent to the Lustre server. + """ + return request, metadata + + def post_get_mirror(self, response: mirror.Mirror) -> mirror.Mirror: + """Post-rpc interceptor for get_mirror + + DEPRECATED. Please use the `post_get_mirror_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Lustre server but before + it is returned to user code. This `post_get_mirror` interceptor runs + before the `post_get_mirror_with_metadata` interceptor. + """ + return response + + def post_get_mirror_with_metadata( + self, response: mirror.Mirror, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[mirror.Mirror, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_mirror + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Lustre server but before it is returned to user code. + + We recommend only using this `post_get_mirror_with_metadata` + interceptor in new development instead of the `post_get_mirror` interceptor. + When both interceptors are used, this `post_get_mirror_with_metadata` interceptor runs after the + `post_get_mirror` interceptor. The (possibly modified) response returned by + `post_get_mirror` will be passed to + `post_get_mirror_with_metadata`. + """ + return response, metadata + def pre_import_data( self, request: transfer.ImportDataRequest, @@ -367,52 +736,198 @@ def post_import_data_with_metadata( """ return response, metadata - def pre_list_instances( + def pre_list_directory_policies( self, - request: instance.ListInstancesRequest, + request: directory_policy.ListDirectoryPoliciesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[instance.ListInstancesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_instances + ) -> Tuple[ + directory_policy.ListDirectoryPoliciesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_directory_policies Override in a subclass to manipulate the request or metadata before they are sent to the Lustre server. """ return request, metadata - def post_list_instances( - self, response: instance.ListInstancesResponse - ) -> instance.ListInstancesResponse: - """Post-rpc interceptor for list_instances + def post_list_directory_policies( + self, response: directory_policy.ListDirectoryPoliciesResponse + ) -> directory_policy.ListDirectoryPoliciesResponse: + """Post-rpc interceptor for list_directory_policies - DEPRECATED. Please use the `post_list_instances_with_metadata` + DEPRECATED. Please use the `post_list_directory_policies_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the Lustre server but before - it is returned to user code. This `post_list_instances` interceptor runs - before the `post_list_instances_with_metadata` interceptor. + it is returned to user code. This `post_list_directory_policies` interceptor runs + before the `post_list_directory_policies_with_metadata` interceptor. """ return response - def post_list_instances_with_metadata( + def post_list_directory_policies_with_metadata( self, - response: instance.ListInstancesResponse, + response: directory_policy.ListDirectoryPoliciesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[instance.ListInstancesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_instances + ) -> Tuple[ + directory_policy.ListDirectoryPoliciesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_directory_policies Override in a subclass to read or manipulate the response or metadata after it is returned by the Lustre server but before it is returned to user code. - We recommend only using this `post_list_instances_with_metadata` - interceptor in new development instead of the `post_list_instances` interceptor. - When both interceptors are used, this `post_list_instances_with_metadata` interceptor runs after the - `post_list_instances` interceptor. The (possibly modified) response returned by + We recommend only using this `post_list_directory_policies_with_metadata` + interceptor in new development instead of the `post_list_directory_policies` interceptor. + When both interceptors are used, this `post_list_directory_policies_with_metadata` interceptor runs after the + `post_list_directory_policies` interceptor. The (possibly modified) response returned by + `post_list_directory_policies` will be passed to + `post_list_directory_policies_with_metadata`. + """ + return response, metadata + + def pre_list_instances( + self, + request: instance.ListInstancesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[instance.ListInstancesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the Lustre server. + """ + return request, metadata + + def post_list_instances( + self, response: instance.ListInstancesResponse + ) -> instance.ListInstancesResponse: + """Post-rpc interceptor for list_instances + + DEPRECATED. Please use the `post_list_instances_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Lustre server but before + it is returned to user code. This `post_list_instances` interceptor runs + before the `post_list_instances_with_metadata` interceptor. + """ + return response + + def post_list_instances_with_metadata( + self, + response: instance.ListInstancesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[instance.ListInstancesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_instances + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Lustre server but before it is returned to user code. + + We recommend only using this `post_list_instances_with_metadata` + interceptor in new development instead of the `post_list_instances` interceptor. + When both interceptors are used, this `post_list_instances_with_metadata` interceptor runs after the + `post_list_instances` interceptor. The (possibly modified) response returned by `post_list_instances` will be passed to `post_list_instances_with_metadata`. """ return response, metadata + def pre_list_mirrors( + self, + request: mirror.ListMirrorsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[mirror.ListMirrorsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_mirrors + + Override in a subclass to manipulate the request or metadata + before they are sent to the Lustre server. + """ + return request, metadata + + def post_list_mirrors( + self, response: mirror.ListMirrorsResponse + ) -> mirror.ListMirrorsResponse: + """Post-rpc interceptor for list_mirrors + + DEPRECATED. Please use the `post_list_mirrors_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Lustre server but before + it is returned to user code. This `post_list_mirrors` interceptor runs + before the `post_list_mirrors_with_metadata` interceptor. + """ + return response + + def post_list_mirrors_with_metadata( + self, + response: mirror.ListMirrorsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[mirror.ListMirrorsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_mirrors + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Lustre server but before it is returned to user code. + + We recommend only using this `post_list_mirrors_with_metadata` + interceptor in new development instead of the `post_list_mirrors` interceptor. + When both interceptors are used, this `post_list_mirrors_with_metadata` interceptor runs after the + `post_list_mirrors` interceptor. The (possibly modified) response returned by + `post_list_mirrors` will be passed to + `post_list_mirrors_with_metadata`. + """ + return response, metadata + + def pre_reschedule_maintenance( + self, + request: instance.RescheduleMaintenanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + instance.RescheduleMaintenanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for reschedule_maintenance + + Override in a subclass to manipulate the request or metadata + before they are sent to the Lustre server. + """ + return request, metadata + + def post_reschedule_maintenance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for reschedule_maintenance + + DEPRECATED. Please use the `post_reschedule_maintenance_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Lustre server but before + it is returned to user code. This `post_reschedule_maintenance` interceptor runs + before the `post_reschedule_maintenance_with_metadata` interceptor. + """ + return response + + def post_reschedule_maintenance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for reschedule_maintenance + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Lustre server but before it is returned to user code. + + We recommend only using this `post_reschedule_maintenance_with_metadata` + interceptor in new development instead of the `post_reschedule_maintenance` interceptor. + When both interceptors are used, this `post_reschedule_maintenance_with_metadata` interceptor runs after the + `post_reschedule_maintenance` interceptor. The (possibly modified) response returned by + `post_reschedule_maintenance` will be passed to + `post_reschedule_maintenance_with_metadata`. + """ + return response, metadata + def pre_update_instance( self, request: gcl_instance.UpdateInstanceRequest, @@ -461,6 +976,52 @@ def post_update_instance_with_metadata( """ return response, metadata + def pre_update_mirror( + self, + request: gcl_mirror.UpdateMirrorRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcl_mirror.UpdateMirrorRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_mirror + + Override in a subclass to manipulate the request or metadata + before they are sent to the Lustre server. + """ + return request, metadata + + def post_update_mirror( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_mirror + + DEPRECATED. Please use the `post_update_mirror_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Lustre server but before + it is returned to user code. This `post_update_mirror` interceptor runs + before the `post_update_mirror_with_metadata` interceptor. + """ + return response + + def post_update_mirror_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_mirror + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Lustre server but before it is returned to user code. + + We recommend only using this `post_update_mirror_with_metadata` + interceptor in new development instead of the `post_update_mirror` interceptor. + When both interceptors are used, this `post_update_mirror_with_metadata` interceptor runs after the + `post_update_mirror` interceptor. The (possibly modified) response returned by + `post_update_mirror` will be passed to + `post_update_mirror_with_metadata`. + """ + return response, metadata + def pre_get_location( self, request: locations_pb2.GetLocationRequest, @@ -511,6 +1072,78 @@ def post_list_locations( """ return response + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Lustre 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 Lustre 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, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Lustre 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 Lustre 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, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Lustre 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 Lustre server but before + it is returned to user code. + """ + return response + def pre_cancel_operation( self, request: operations_pb2.CancelOperationRequest, @@ -754,9 +1387,11 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateInstance(_BaseLustreRestTransport._BaseCreateInstance, LustreRestStub): + class _CreateDirectoryPolicy( + _BaseLustreRestTransport._BaseCreateDirectoryPolicy, LustreRestStub + ): def __hash__(self): - return hash("LustreRestTransport.CreateInstance") + return hash("LustreRestTransport.CreateDirectoryPolicy") @staticmethod def _get_response( @@ -783,17 +1418,18 @@ def _get_response( def __call__( self, - request: gcl_instance.CreateInstanceRequest, + request: gcl_directory_policy.CreateDirectoryPolicyRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the create instance method over HTTP. + r"""Call the create directory policy method over HTTP. Args: - request (~.gcl_instance.CreateInstanceRequest): - The request object. Message for creating a Instance + request (~.gcl_directory_policy.CreateDirectoryPolicyRequest): + The request object. Request message for + CreateDirectoryPolicy. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -810,16 +1446,1908 @@ def __call__( """ - http_options = ( - _BaseLustreRestTransport._BaseCreateInstance._get_http_options() - ) - request, metadata = self._interceptor.pre_create_instance(request, metadata) + http_options = ( + _BaseLustreRestTransport._BaseCreateDirectoryPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_create_directory_policy( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseLustreRestTransport._BaseCreateDirectoryPolicy, + "_BaseCreateDirectoryPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.lustre_v1.LustreClient.CreateDirectoryPolicy", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "CreateDirectoryPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LustreRestTransport._CreateDirectoryPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_directory_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_directory_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.lustre_v1.LustreClient.create_directory_policy", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "CreateDirectoryPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateInstance(_BaseLustreRestTransport._BaseCreateInstance, LustreRestStub): + def __hash__(self): + return hash("LustreRestTransport.CreateInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gcl_instance.CreateInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create instance method over HTTP. + + Args: + request (~.gcl_instance.CreateInstanceRequest): + The request object. Message for creating a Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseLustreRestTransport._BaseCreateInstance._get_http_options() + ) + request, metadata = self._interceptor.pre_create_instance(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseLustreRestTransport._BaseCreateInstance, + "_BaseCreateInstance__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.lustre_v1.LustreClient.CreateInstance", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "CreateInstance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LustreRestTransport._CreateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_instance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.lustre_v1.LustreClient.create_instance", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "CreateInstance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateMirror(_BaseLustreRestTransport._BaseCreateMirror, LustreRestStub): + def __hash__(self): + return hash("LustreRestTransport.CreateMirror") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gcl_mirror.CreateMirrorRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create mirror method over HTTP. + + Args: + request (~.gcl_mirror.CreateMirrorRequest): + The request object. Request for CreateMirror. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseLustreRestTransport._BaseCreateMirror._get_http_options() + ) + request, metadata = self._interceptor.pre_create_mirror(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseLustreRestTransport._BaseCreateMirror, + "_BaseCreateMirror__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.lustre_v1.LustreClient.CreateMirror", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "CreateMirror", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LustreRestTransport._CreateMirror._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_mirror(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_mirror_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.lustre_v1.LustreClient.create_mirror", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "CreateMirror", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteDirectoryPolicy( + _BaseLustreRestTransport._BaseDeleteDirectoryPolicy, LustreRestStub + ): + def __hash__(self): + return hash("LustreRestTransport.DeleteDirectoryPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: directory_policy.DeleteDirectoryPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete directory policy method over HTTP. + + Args: + request (~.directory_policy.DeleteDirectoryPolicyRequest): + The request object. Request message for + DeleteDirectoryPolicy. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseLustreRestTransport._BaseDeleteDirectoryPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_directory_policy( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseLustreRestTransport._BaseDeleteDirectoryPolicy, + "_BaseDeleteDirectoryPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.lustre_v1.LustreClient.DeleteDirectoryPolicy", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "DeleteDirectoryPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LustreRestTransport._DeleteDirectoryPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_directory_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_directory_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.lustre_v1.LustreClient.delete_directory_policy", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "DeleteDirectoryPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteInstance(_BaseLustreRestTransport._BaseDeleteInstance, LustreRestStub): + def __hash__(self): + return hash("LustreRestTransport.DeleteInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: instance.DeleteInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete instance method over HTTP. + + Args: + request (~.instance.DeleteInstanceRequest): + The request object. Message for deleting a Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseLustreRestTransport._BaseDeleteInstance._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_instance(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseLustreRestTransport._BaseDeleteInstance, + "_BaseDeleteInstance__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.lustre_v1.LustreClient.DeleteInstance", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "DeleteInstance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LustreRestTransport._DeleteInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_instance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.lustre_v1.LustreClient.delete_instance", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "DeleteInstance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteMirror(_BaseLustreRestTransport._BaseDeleteMirror, LustreRestStub): + def __hash__(self): + return hash("LustreRestTransport.DeleteMirror") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: mirror.DeleteMirrorRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete mirror method over HTTP. + + Args: + request (~.mirror.DeleteMirrorRequest): + The request object. Request for DeleteMirror. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseLustreRestTransport._BaseDeleteMirror._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_mirror(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseLustreRestTransport._BaseDeleteMirror, + "_BaseDeleteMirror__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.lustre_v1.LustreClient.DeleteMirror", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "DeleteMirror", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LustreRestTransport._DeleteMirror._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_mirror(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_mirror_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.lustre_v1.LustreClient.delete_mirror", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "DeleteMirror", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ExportData(_BaseLustreRestTransport._BaseExportData, LustreRestStub): + def __hash__(self): + return hash("LustreRestTransport.ExportData") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: transfer.ExportDataRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the export data method over HTTP. + + Args: + request (~.transfer.ExportDataRequest): + The request object. Export data from Managed Lustre to a + Cloud Storage bucket. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseLustreRestTransport._BaseExportData._get_http_options() + request, metadata = self._interceptor.pre_export_data(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseLustreRestTransport._BaseExportData, + "_BaseExportData__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.lustre_v1.LustreClient.ExportData", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "ExportData", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LustreRestTransport._ExportData._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_export_data(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_export_data_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.lustre_v1.LustreClient.export_data", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "ExportData", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetDirectoryPolicy( + _BaseLustreRestTransport._BaseGetDirectoryPolicy, LustreRestStub + ): + def __hash__(self): + return hash("LustreRestTransport.GetDirectoryPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: directory_policy.GetDirectoryPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> directory_policy.DirectoryPolicy: + r"""Call the get directory policy method over HTTP. + + Args: + request (~.directory_policy.GetDirectoryPolicyRequest): + The request object. Request message for + GetDirectoryPolicy. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.directory_policy.DirectoryPolicy: + A directory policy for a Managed + Lustre instance. + + """ + + http_options = ( + _BaseLustreRestTransport._BaseGetDirectoryPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_get_directory_policy( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseLustreRestTransport._BaseGetDirectoryPolicy, + "_BaseGetDirectoryPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.lustre_v1.LustreClient.GetDirectoryPolicy", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "GetDirectoryPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LustreRestTransport._GetDirectoryPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = directory_policy.DirectoryPolicy() + pb_resp = directory_policy.DirectoryPolicy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_directory_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_directory_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = directory_policy.DirectoryPolicy.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.lustre_v1.LustreClient.get_directory_policy", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "GetDirectoryPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetInstance(_BaseLustreRestTransport._BaseGetInstance, LustreRestStub): + def __hash__(self): + return hash("LustreRestTransport.GetInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: instance.GetInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> instance.Instance: + r"""Call the get instance method over HTTP. + + Args: + request (~.instance.GetInstanceRequest): + The request object. Message for getting a Instance + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.instance.Instance: + A Managed Lustre instance. + """ + + http_options = _BaseLustreRestTransport._BaseGetInstance._get_http_options() + request, metadata = self._interceptor.pre_get_instance(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseLustreRestTransport._BaseGetInstance, + "_BaseGetInstance__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.lustre_v1.LustreClient.GetInstance", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "GetInstance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LustreRestTransport._GetInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = instance.Instance() + pb_resp = instance.Instance.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_instance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = instance.Instance.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.lustre_v1.LustreClient.get_instance", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "GetInstance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetMirror(_BaseLustreRestTransport._BaseGetMirror, LustreRestStub): + def __hash__(self): + return hash("LustreRestTransport.GetMirror") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: mirror.GetMirrorRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> mirror.Mirror: + r"""Call the get mirror method over HTTP. + + Args: + request (~.mirror.GetMirrorRequest): + The request object. Request for GetMirror. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.mirror.Mirror: + Represents a Cloud Storage mirror. + """ + + http_options = _BaseLustreRestTransport._BaseGetMirror._get_http_options() + request, metadata = self._interceptor.pre_get_mirror(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseLustreRestTransport._BaseGetMirror, + "_BaseGetMirror__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.lustre_v1.LustreClient.GetMirror", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "GetMirror", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LustreRestTransport._GetMirror._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = mirror.Mirror() + pb_resp = mirror.Mirror.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_mirror(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_mirror_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = mirror.Mirror.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.lustre_v1.LustreClient.get_mirror", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "GetMirror", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ImportData(_BaseLustreRestTransport._BaseImportData, LustreRestStub): + def __hash__(self): + return hash("LustreRestTransport.ImportData") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: transfer.ImportDataRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the import data method over HTTP. + + Args: + request (~.transfer.ImportDataRequest): + The request object. Message for importing data to Lustre. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseLustreRestTransport._BaseImportData._get_http_options() + request, metadata = self._interceptor.pre_import_data(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseLustreRestTransport._BaseImportData, + "_BaseImportData__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.lustre_v1.LustreClient.ImportData", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "ImportData", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LustreRestTransport._ImportData._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_import_data(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_import_data_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.lustre_v1.LustreClient.import_data", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "ImportData", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListDirectoryPolicies( + _BaseLustreRestTransport._BaseListDirectoryPolicies, LustreRestStub + ): + def __hash__(self): + return hash("LustreRestTransport.ListDirectoryPolicies") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: directory_policy.ListDirectoryPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> directory_policy.ListDirectoryPoliciesResponse: + r"""Call the list directory policies method over HTTP. + + Args: + request (~.directory_policy.ListDirectoryPoliciesRequest): + The request object. Request message for + ListDirectoryPolicies. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.directory_policy.ListDirectoryPoliciesResponse: + Response message for + ListDirectoryPolicies. + + """ + + http_options = ( + _BaseLustreRestTransport._BaseListDirectoryPolicies._get_http_options() + ) + request, metadata = self._interceptor.pre_list_directory_policies( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseLustreRestTransport._BaseListDirectoryPolicies, + "_BaseListDirectoryPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.lustre_v1.LustreClient.ListDirectoryPolicies", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "ListDirectoryPolicies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LustreRestTransport._ListDirectoryPolicies._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = directory_policy.ListDirectoryPoliciesResponse() + pb_resp = directory_policy.ListDirectoryPoliciesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_directory_policies(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_directory_policies_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + directory_policy.ListDirectoryPoliciesResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.lustre_v1.LustreClient.list_directory_policies", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "ListDirectoryPolicies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListInstances(_BaseLustreRestTransport._BaseListInstances, LustreRestStub): + def __hash__(self): + return hash("LustreRestTransport.ListInstances") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: instance.ListInstancesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> instance.ListInstancesResponse: + r"""Call the list instances method over HTTP. + + Args: + request (~.instance.ListInstancesRequest): + The request object. Message for requesting list of + Instances + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.instance.ListInstancesResponse: + Message for response to listing + Instances + + """ + + http_options = ( + _BaseLustreRestTransport._BaseListInstances._get_http_options() + ) + request, metadata = self._interceptor.pre_list_instances(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseLustreRestTransport._BaseListInstances, + "_BaseListInstances__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.lustre_v1.LustreClient.ListInstances", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "ListInstances", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LustreRestTransport._ListInstances._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = instance.ListInstancesResponse() + pb_resp = instance.ListInstancesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_instances(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_instances_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = instance.ListInstancesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.lustre_v1.LustreClient.list_instances", + extra={ + "serviceName": "google.cloud.lustre.v1.Lustre", + "rpcName": "ListInstances", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListMirrors(_BaseLustreRestTransport._BaseListMirrors, LustreRestStub): + def __hash__(self): + return hash("LustreRestTransport.ListMirrors") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: mirror.ListMirrorsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> mirror.ListMirrorsResponse: + r"""Call the list mirrors method over HTTP. + + Args: + request (~.mirror.ListMirrorsRequest): + The request object. Request for ListMirrors. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.mirror.ListMirrorsResponse: + Response for ListMirrors. + """ + + http_options = _BaseLustreRestTransport._BaseListMirrors._get_http_options() + request, metadata = self._interceptor.pre_list_mirrors(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseLustreRestTransport._BaseCreateInstance, - "_BaseCreateInstance__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseLustreRestTransport._BaseListMirrors, + "_BaseListMirrors__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -843,24 +3371,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.lustre_v1.LustreClient.CreateInstance", + f"Sending request for google.cloud.lustre_v1.LustreClient.ListMirrors", extra={ "serviceName": "google.cloud.lustre.v1.Lustre", - "rpcName": "CreateInstance", + "rpcName": "ListMirrors", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LustreRestTransport._CreateInstance._get_response( + response = LustreRestTransport._ListMirrors._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -869,19 +3396,21 @@ def __call__( 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 = mirror.ListMirrorsResponse() + pb_resp = mirror.ListMirrorsResponse.pb(resp) - resp = self._interceptor.post_create_instance(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_mirrors(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_instance_with_metadata( + resp, _ = self._interceptor.post_list_mirrors_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = json_format.MessageToJson(resp) + response_payload = mirror.ListMirrorsResponse.to_json(response) except: response_payload = None http_response = { @@ -890,19 +3419,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.lustre_v1.LustreClient.create_instance", + "Received response for google.cloud.lustre_v1.LustreClient.list_mirrors", extra={ "serviceName": "google.cloud.lustre.v1.Lustre", - "rpcName": "CreateInstance", + "rpcName": "ListMirrors", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteInstance(_BaseLustreRestTransport._BaseDeleteInstance, LustreRestStub): + class _RescheduleMaintenance( + _BaseLustreRestTransport._BaseRescheduleMaintenance, LustreRestStub + ): def __hash__(self): - return hash("LustreRestTransport.DeleteInstance") + return hash("LustreRestTransport.RescheduleMaintenance") @staticmethod def _get_response( @@ -923,22 +3454,25 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: instance.DeleteInstanceRequest, + request: instance.RescheduleMaintenanceRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the delete instance method over HTTP. + r"""Call the reschedule maintenance method over HTTP. Args: - request (~.instance.DeleteInstanceRequest): - The request object. Message for deleting a Instance + request (~.instance.RescheduleMaintenanceRequest): + The request object. Message for requesting to reschedule + a maintenance event for a specific + instance. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -956,15 +3490,17 @@ def __call__( """ http_options = ( - _BaseLustreRestTransport._BaseDeleteInstance._get_http_options() + _BaseLustreRestTransport._BaseRescheduleMaintenance._get_http_options() + ) + request, metadata = self._interceptor.pre_reschedule_maintenance( + request, metadata ) - request, metadata = self._interceptor.pre_delete_instance(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseLustreRestTransport._BaseDeleteInstance, - "_BaseDeleteInstance__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseLustreRestTransport._BaseRescheduleMaintenance, + "_BaseRescheduleMaintenance__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -988,23 +3524,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.lustre_v1.LustreClient.DeleteInstance", + f"Sending request for google.cloud.lustre_v1.LustreClient.RescheduleMaintenance", extra={ "serviceName": "google.cloud.lustre.v1.Lustre", - "rpcName": "DeleteInstance", + "rpcName": "RescheduleMaintenance", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LustreRestTransport._DeleteInstance._get_response( + response = LustreRestTransport._RescheduleMaintenance._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1016,9 +3553,9 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_instance(resp) + resp = self._interceptor.post_reschedule_maintenance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_instance_with_metadata( + resp, _ = self._interceptor.post_reschedule_maintenance_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -1034,19 +3571,19 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.lustre_v1.LustreClient.delete_instance", + "Received response for google.cloud.lustre_v1.LustreClient.reschedule_maintenance", extra={ "serviceName": "google.cloud.lustre.v1.Lustre", - "rpcName": "DeleteInstance", + "rpcName": "RescheduleMaintenance", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ExportData(_BaseLustreRestTransport._BaseExportData, LustreRestStub): + class _UpdateInstance(_BaseLustreRestTransport._BaseUpdateInstance, LustreRestStub): def __hash__(self): - return hash("LustreRestTransport.ExportData") + return hash("LustreRestTransport.UpdateInstance") @staticmethod def _get_response( @@ -1073,18 +3610,17 @@ def _get_response( def __call__( self, - request: transfer.ExportDataRequest, + request: gcl_instance.UpdateInstanceRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the export data method over HTTP. + r"""Call the update instance method over HTTP. Args: - request (~.transfer.ExportDataRequest): - The request object. Export data from Managed Lustre to a - Cloud Storage bucket. + request (~.gcl_instance.UpdateInstanceRequest): + The request object. Message for updating a Instance retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1101,14 +3637,16 @@ def __call__( """ - http_options = _BaseLustreRestTransport._BaseExportData._get_http_options() - request, metadata = self._interceptor.pre_export_data(request, metadata) + http_options = ( + _BaseLustreRestTransport._BaseUpdateInstance._get_http_options() + ) + request, metadata = self._interceptor.pre_update_instance(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseLustreRestTransport._BaseExportData, - "_BaseExportData__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseLustreRestTransport._BaseUpdateInstance, + "_BaseUpdateInstance__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -1132,17 +3670,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.lustre_v1.LustreClient.ExportData", + f"Sending request for google.cloud.lustre_v1.LustreClient.UpdateInstance", extra={ "serviceName": "google.cloud.lustre.v1.Lustre", - "rpcName": "ExportData", + "rpcName": "UpdateInstance", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LustreRestTransport._ExportData._get_response( + response = LustreRestTransport._UpdateInstance._get_response( self._host, metadata, query_params, @@ -1161,9 +3699,9 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_export_data(resp) + resp = self._interceptor.post_update_instance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_export_data_with_metadata( + resp, _ = self._interceptor.post_update_instance_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -1179,19 +3717,19 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.lustre_v1.LustreClient.export_data", + "Received response for google.cloud.lustre_v1.LustreClient.update_instance", extra={ "serviceName": "google.cloud.lustre.v1.Lustre", - "rpcName": "ExportData", + "rpcName": "UpdateInstance", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetInstance(_BaseLustreRestTransport._BaseGetInstance, LustreRestStub): + class _UpdateMirror(_BaseLustreRestTransport._BaseUpdateMirror, LustreRestStub): def __hash__(self): - return hash("LustreRestTransport.GetInstance") + return hash("LustreRestTransport.UpdateMirror") @staticmethod def _get_response( @@ -1212,22 +3750,23 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: instance.GetInstanceRequest, + request: gcl_mirror.UpdateMirrorRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> instance.Instance: - r"""Call the get instance method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the update mirror method over HTTP. Args: - request (~.instance.GetInstanceRequest): - The request object. Message for getting a Instance + request (~.gcl_mirror.UpdateMirrorRequest): + The request object. Request for UpdateMirror. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1237,18 +3776,23 @@ def __call__( be of type `bytes`. Returns: - ~.instance.Instance: - A Managed Lustre instance. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + """ - http_options = _BaseLustreRestTransport._BaseGetInstance._get_http_options() - request, metadata = self._interceptor.pre_get_instance(request, metadata) + http_options = ( + _BaseLustreRestTransport._BaseUpdateMirror._get_http_options() + ) + request, metadata = self._interceptor.pre_update_mirror(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseLustreRestTransport._BaseGetInstance, - "_BaseGetInstance__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseLustreRestTransport._BaseUpdateMirror, + "_BaseUpdateMirror__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -1272,23 +3816,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.lustre_v1.LustreClient.GetInstance", + f"Sending request for google.cloud.lustre_v1.LustreClient.UpdateMirror", extra={ "serviceName": "google.cloud.lustre.v1.Lustre", - "rpcName": "GetInstance", + "rpcName": "UpdateMirror", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LustreRestTransport._GetInstance._get_response( + response = LustreRestTransport._UpdateMirror._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1297,21 +3842,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = instance.Instance() - pb_resp = instance.Instance.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_instance(resp) + resp = self._interceptor.post_update_mirror(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_instance_with_metadata( + resp, _ = self._interceptor.post_update_mirror_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = instance.Instance.to_json(response) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -1320,19 +3863,166 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.lustre_v1.LustreClient.get_instance", + "Received response for google.cloud.lustre_v1.LustreClient.update_mirror", extra={ "serviceName": "google.cloud.lustre.v1.Lustre", - "rpcName": "GetInstance", + "rpcName": "UpdateMirror", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ImportData(_BaseLustreRestTransport._BaseImportData, LustreRestStub): + @property + def create_directory_policy( + self, + ) -> Callable[ + [gcl_directory_policy.CreateDirectoryPolicyRequest], 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._CreateDirectoryPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_instance( + self, + ) -> Callable[[gcl_instance.CreateInstanceRequest], 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._CreateInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_mirror( + self, + ) -> Callable[[gcl_mirror.CreateMirrorRequest], 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._CreateMirror(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_directory_policy( + self, + ) -> Callable[ + [directory_policy.DeleteDirectoryPolicyRequest], 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._DeleteDirectoryPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_instance( + self, + ) -> Callable[[instance.DeleteInstanceRequest], 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._DeleteInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_mirror( + self, + ) -> Callable[[mirror.DeleteMirrorRequest], 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._DeleteMirror(self._session, self._host, self._interceptor) # type: ignore + + @property + def export_data( + self, + ) -> Callable[[transfer.ExportDataRequest], 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._ExportData(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_directory_policy( + self, + ) -> Callable[ + [directory_policy.GetDirectoryPolicyRequest], directory_policy.DirectoryPolicy + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDirectoryPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_instance( + self, + ) -> Callable[[instance.GetInstanceRequest], instance.Instance]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_mirror(self) -> Callable[[mirror.GetMirrorRequest], mirror.Mirror]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetMirror(self._session, self._host, self._interceptor) # type: ignore + + @property + def import_data( + self, + ) -> Callable[[transfer.ImportDataRequest], 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._ImportData(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_directory_policies( + self, + ) -> Callable[ + [directory_policy.ListDirectoryPoliciesRequest], + directory_policy.ListDirectoryPoliciesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDirectoryPolicies(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_instances( + self, + ) -> Callable[[instance.ListInstancesRequest], instance.ListInstancesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListInstances(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_mirrors( + self, + ) -> Callable[[mirror.ListMirrorsRequest], mirror.ListMirrorsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListMirrors(self._session, self._host, self._interceptor) # type: ignore + + @property + def reschedule_maintenance( + self, + ) -> Callable[[instance.RescheduleMaintenanceRequest], 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._RescheduleMaintenance(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_instance( + self, + ) -> Callable[[gcl_instance.UpdateInstanceRequest], 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._UpdateInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_mirror( + self, + ) -> Callable[[gcl_mirror.UpdateMirrorRequest], 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._UpdateMirror(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(_BaseLustreRestTransport._BaseGetLocation, LustreRestStub): def __hash__(self): - return hash("LustreRestTransport.ImportData") + return hash("LustreRestTransport.GetLocation") @staticmethod def _get_response( @@ -1353,50 +4043,45 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, ) return response def __call__( self, - request: transfer.ImportDataRequest, + request: locations_pb2.GetLocationRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the import data method over HTTP. + ) -> locations_pb2.Location: + r"""Call the get location method over HTTP. Args: - request (~.transfer.ImportDataRequest): - The request object. Message for importing data to Lustre. + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + locations_pb2.Location: Response from GetLocation method. """ - http_options = _BaseLustreRestTransport._BaseImportData._get_http_options() - request, metadata = self._interceptor.pre_import_data(request, metadata) + http_options = _BaseLustreRestTransport._BaseGetLocation._get_http_options() + request, metadata = self._interceptor.pre_get_location(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseLustreRestTransport._BaseImportData, - "_BaseImportData__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseLustreRestTransport._BaseGetLocation, + "_BaseGetLocation__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), - rest_numeric_enums=True, + rest_numeric_enums=False, ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -1407,7 +4092,7 @@ def __call__( ) method = transcoded_request["method"] try: - request_payload = type(request).to_json(request) + request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { @@ -1417,24 +4102,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.lustre_v1.LustreClient.ImportData", + f"Sending request for google.cloud.lustre_v1.LustreClient.GetLocation", extra={ "serviceName": "google.cloud.lustre.v1.Lustre", - "rpcName": "ImportData", + "rpcName": "GetLocation", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LustreRestTransport._ImportData._get_response( + response = LustreRestTransport._GetLocation._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1442,15 +4126,10 @@ def __call__( 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_import_data(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_import_data_with_metadata( - resp, response_metadata - ) + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER @@ -1464,19 +4143,23 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.lustre_v1.LustreClient.import_data", + "Received response for google.cloud.lustre_v1.LustreAsyncClient.GetLocation", extra={ "serviceName": "google.cloud.lustre.v1.Lustre", - "rpcName": "ImportData", - "metadata": http_response["headers"], + "rpcName": "GetLocation", "httpResponse": http_response, + "metadata": http_response["headers"], }, ) return resp - class _ListInstances(_BaseLustreRestTransport._BaseListInstances, LustreRestStub): + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(_BaseLustreRestTransport._BaseListLocations, LustreRestStub): def __hash__(self): - return hash("LustreRestTransport.ListInstances") + return hash("LustreRestTransport.ListLocations") @staticmethod def _get_response( @@ -1502,18 +4185,17 @@ def _get_response( def __call__( self, - request: instance.ListInstancesRequest, + request: locations_pb2.ListLocationsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> instance.ListInstancesResponse: - r"""Call the list instances method over HTTP. + ) -> locations_pb2.ListLocationsResponse: + r"""Call the list locations method over HTTP. Args: - request (~.instance.ListInstancesRequest): - The request object. Message for requesting list of - Instances + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1523,25 +4205,22 @@ def __call__( be of type `bytes`. Returns: - ~.instance.ListInstancesResponse: - Message for response to listing - Instances - + locations_pb2.ListLocationsResponse: Response from ListLocations method. """ http_options = ( - _BaseLustreRestTransport._BaseListInstances._get_http_options() + _BaseLustreRestTransport._BaseListLocations._get_http_options() ) - request, metadata = self._interceptor.pre_list_instances(request, metadata) + request, metadata = self._interceptor.pre_list_locations(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseLustreRestTransport._BaseListInstances, - "_BaseListInstances__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseLustreRestTransport._BaseListLocations, + "_BaseListLocations__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), - rest_numeric_enums=True, + rest_numeric_enums=False, ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -1552,7 +4231,7 @@ def __call__( ) method = transcoded_request["method"] try: - request_payload = type(request).to_json(request) + request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { @@ -1562,17 +4241,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.lustre_v1.LustreClient.ListInstances", + f"Sending request for google.cloud.lustre_v1.LustreClient.ListLocations", extra={ "serviceName": "google.cloud.lustre.v1.Lustre", - "rpcName": "ListInstances", + "rpcName": "ListLocations", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LustreRestTransport._ListInstances._get_response( + response = LustreRestTransport._ListLocations._get_response( self._host, metadata, query_params, @@ -1586,22 +4265,15 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - # Return the response - resp = instance.ListInstancesResponse() - pb_resp = instance.ListInstancesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_instances(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_instances_with_metadata( - resp, response_metadata - ) + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = instance.ListInstancesResponse.to_json(response) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -1610,19 +4282,23 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.lustre_v1.LustreClient.list_instances", + "Received response for google.cloud.lustre_v1.LustreAsyncClient.ListLocations", extra={ "serviceName": "google.cloud.lustre.v1.Lustre", - "rpcName": "ListInstances", - "metadata": http_response["headers"], + "rpcName": "ListLocations", "httpResponse": http_response, + "metadata": http_response["headers"], }, ) return resp - class _UpdateInstance(_BaseLustreRestTransport._BaseUpdateInstance, LustreRestStub): + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(_BaseLustreRestTransport._BaseGetIamPolicy, LustreRestStub): def __hash__(self): - return hash("LustreRestTransport.UpdateInstance") + return hash("LustreRestTransport.GetIamPolicy") @staticmethod def _get_response( @@ -1643,23 +4319,22 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, ) return response def __call__( self, - request: gcl_instance.UpdateInstanceRequest, + request: iam_policy_pb2.GetIamPolicyRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the update instance method over HTTP. + ) -> policy_pb2.Policy: + r"""Call the get iam policy method over HTTP. Args: - request (~.gcl_instance.UpdateInstanceRequest): - The request object. Message for updating a Instance + 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. @@ -1669,26 +4344,22 @@ def __call__( be of type `bytes`. Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - + policy_pb2.Policy: Response from GetIamPolicy method. """ http_options = ( - _BaseLustreRestTransport._BaseUpdateInstance._get_http_options() + _BaseLustreRestTransport._BaseGetIamPolicy._get_http_options() ) - request, metadata = self._interceptor.pre_update_instance(request, metadata) + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseLustreRestTransport._BaseUpdateInstance, - "_BaseUpdateInstance__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseLustreRestTransport._BaseGetIamPolicy, + "_BaseGetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), - rest_numeric_enums=True, + rest_numeric_enums=False, ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -1699,7 +4370,7 @@ def __call__( ) method = transcoded_request["method"] try: - request_payload = type(request).to_json(request) + request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { @@ -1709,24 +4380,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.lustre_v1.LustreClient.UpdateInstance", + f"Sending request for google.cloud.lustre_v1.LustreClient.GetIamPolicy", extra={ "serviceName": "google.cloud.lustre.v1.Lustre", - "rpcName": "UpdateInstance", + "rpcName": "GetIamPolicy", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LustreRestTransport._UpdateInstance._get_response( + response = LustreRestTransport._GetIamPolicy._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1734,15 +4404,10 @@ def __call__( 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_instance(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_instance_with_metadata( - resp, response_metadata - ) + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER @@ -1756,79 +4421,23 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.lustre_v1.LustreClient.update_instance", + "Received response for google.cloud.lustre_v1.LustreAsyncClient.GetIamPolicy", extra={ "serviceName": "google.cloud.lustre.v1.Lustre", - "rpcName": "UpdateInstance", - "metadata": http_response["headers"], + "rpcName": "GetIamPolicy", "httpResponse": http_response, + "metadata": http_response["headers"], }, ) return resp @property - def create_instance( - self, - ) -> Callable[[gcl_instance.CreateInstanceRequest], 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._CreateInstance(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_instance( - self, - ) -> Callable[[instance.DeleteInstanceRequest], 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._DeleteInstance(self._session, self._host, self._interceptor) # type: ignore - - @property - def export_data( - self, - ) -> Callable[[transfer.ExportDataRequest], 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._ExportData(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_instance( - self, - ) -> Callable[[instance.GetInstanceRequest], instance.Instance]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore - - @property - def import_data( - self, - ) -> Callable[[transfer.ImportDataRequest], 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._ImportData(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_instances( - self, - ) -> Callable[[instance.ListInstancesRequest], instance.ListInstancesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListInstances(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_instance( - self, - ) -> Callable[[gcl_instance.UpdateInstanceRequest], 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._UpdateInstance(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - class _GetLocation(_BaseLustreRestTransport._BaseGetLocation, LustreRestStub): + class _SetIamPolicy(_BaseLustreRestTransport._BaseSetIamPolicy, LustreRestStub): def __hash__(self): - return hash("LustreRestTransport.GetLocation") + return hash("LustreRestTransport.SetIamPolicy") @staticmethod def _get_response( @@ -1849,22 +4458,23 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: locations_pb2.GetLocationRequest, + request: iam_policy_pb2.SetIamPolicyRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.Location: - r"""Call the get location method over HTTP. + ) -> policy_pb2.Policy: + r"""Call the set iam policy method over HTTP. Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. + 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. @@ -1874,17 +4484,19 @@ def __call__( be of type `bytes`. Returns: - locations_pb2.Location: Response from GetLocation method. + policy_pb2.Policy: Response from SetIamPolicy method. """ - http_options = _BaseLustreRestTransport._BaseGetLocation._get_http_options() - request, metadata = self._interceptor.pre_get_location(request, metadata) + http_options = ( + _BaseLustreRestTransport._BaseSetIamPolicy._get_http_options() + ) + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseLustreRestTransport._BaseGetLocation, - "_BaseGetLocation__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseLustreRestTransport._BaseSetIamPolicy, + "_BaseSetIamPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=False, @@ -1908,23 +4520,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.lustre_v1.LustreClient.GetLocation", + f"Sending request for google.cloud.lustre_v1.LustreClient.SetIamPolicy", extra={ "serviceName": "google.cloud.lustre.v1.Lustre", - "rpcName": "GetLocation", + "rpcName": "SetIamPolicy", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LustreRestTransport._GetLocation._get_response( + response = LustreRestTransport._SetIamPolicy._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1933,9 +4546,9 @@ def __call__( raise core_exceptions.from_http_response(response) content = response.content.decode("utf-8") - resp = locations_pb2.Location() + resp = policy_pb2.Policy() resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_location(resp) + resp = self._interceptor.post_set_iam_policy(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER @@ -1949,10 +4562,10 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.lustre_v1.LustreAsyncClient.GetLocation", + "Received response for google.cloud.lustre_v1.LustreAsyncClient.SetIamPolicy", extra={ "serviceName": "google.cloud.lustre.v1.Lustre", - "rpcName": "GetLocation", + "rpcName": "SetIamPolicy", "httpResponse": http_response, "metadata": http_response["headers"], }, @@ -1960,12 +4573,14 @@ def __call__( return resp @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - class _ListLocations(_BaseLustreRestTransport._BaseListLocations, LustreRestStub): + class _TestIamPermissions( + _BaseLustreRestTransport._BaseTestIamPermissions, LustreRestStub + ): def __hash__(self): - return hash("LustreRestTransport.ListLocations") + return hash("LustreRestTransport.TestIamPermissions") @staticmethod def _get_response( @@ -1986,22 +4601,23 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: locations_pb2.ListLocationsRequest, + request: iam_policy_pb2.TestIamPermissionsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Call the list locations method over HTTP. + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Call the test iam permissions method over HTTP. Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. + 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. @@ -2011,19 +4627,21 @@ def __call__( be of type `bytes`. Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. """ http_options = ( - _BaseLustreRestTransport._BaseListLocations._get_http_options() + _BaseLustreRestTransport._BaseTestIamPermissions._get_http_options() + ) + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata ) - request, metadata = self._interceptor.pre_list_locations(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseLustreRestTransport._BaseListLocations, - "_BaseListLocations__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseLustreRestTransport._BaseTestIamPermissions, + "_BaseTestIamPermissions__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=False, @@ -2047,23 +4665,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.lustre_v1.LustreClient.ListLocations", + f"Sending request for google.cloud.lustre_v1.LustreClient.TestIamPermissions", extra={ "serviceName": "google.cloud.lustre.v1.Lustre", - "rpcName": "ListLocations", + "rpcName": "TestIamPermissions", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = LustreRestTransport._ListLocations._get_response( + response = LustreRestTransport._TestIamPermissions._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2072,9 +4691,9 @@ def __call__( raise core_exceptions.from_http_response(response) content = response.content.decode("utf-8") - resp = locations_pb2.ListLocationsResponse() + resp = iam_policy_pb2.TestIamPermissionsResponse() resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_locations(resp) + resp = self._interceptor.post_test_iam_permissions(resp) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER @@ -2088,10 +4707,10 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.lustre_v1.LustreAsyncClient.ListLocations", + "Received response for google.cloud.lustre_v1.LustreAsyncClient.TestIamPermissions", extra={ "serviceName": "google.cloud.lustre.v1.Lustre", - "rpcName": "ListLocations", + "rpcName": "TestIamPermissions", "httpResponse": http_response, "metadata": http_response["headers"], }, diff --git a/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/rest_base.py b/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/rest_base.py index b45d01611946..3300b4bb10c9 100644 --- a/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/rest_base.py +++ b/packages/google-cloud-lustre/google/cloud/lustre_v1/services/lustre/transports/rest_base.py @@ -19,11 +19,17 @@ from google.api_core import gapic_v1, path_template from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -from google.cloud.lustre_v1.types import instance, transfer +from google.cloud.lustre_v1.types import directory_policy, instance, mirror, transfer +from google.cloud.lustre_v1.types import directory_policy as gcl_directory_policy from google.cloud.lustre_v1.types import instance as gcl_instance +from google.cloud.lustre_v1.types import mirror as gcl_mirror from .base import DEFAULT_CLIENT_INFO, LustreTransport @@ -90,6 +96,25 @@ def __init__( api_audience=api_audience, ) + class _BaseCreateDirectoryPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "directoryPolicyId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/instances/*}/directoryPolicies", + "body": "directory_policy", + }, + ] + return http_options + class _BaseCreateInstance: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -109,6 +134,41 @@ def _get_http_options(): ] return http_options + class _BaseCreateMirror: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "mirrorId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/instances/*}/mirrors", + "body": "mirror", + }, + ] + return http_options + + class _BaseDeleteDirectoryPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/instances/*/directoryPolicies/*}", + }, + ] + return http_options + class _BaseDeleteInstance: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -125,6 +185,22 @@ def _get_http_options(): ] return http_options + class _BaseDeleteMirror: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/instances/*/mirrors/*}", + }, + ] + return http_options + class _BaseExportData: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -142,6 +218,22 @@ def _get_http_options(): ] return http_options + class _BaseGetDirectoryPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/instances/*/directoryPolicies/*}", + }, + ] + return http_options + class _BaseGetInstance: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -158,6 +250,22 @@ def _get_http_options(): ] return http_options + class _BaseGetMirror: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/instances/*/mirrors/*}", + }, + ] + return http_options + class _BaseImportData: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -175,6 +283,22 @@ def _get_http_options(): ] return http_options + class _BaseListDirectoryPolicies: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/instances/*}/directoryPolicies", + }, + ] + return http_options + class _BaseListInstances: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -191,6 +315,39 @@ def _get_http_options(): ] return http_options + class _BaseListMirrors: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/instances/*}/mirrors", + }, + ] + return http_options + + class _BaseRescheduleMaintenance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/instances/*}:rescheduleMaintenance", + "body": "*", + }, + ] + return http_options + class _BaseUpdateInstance: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -208,6 +365,23 @@ def _get_http_options(): ] return http_options + class _BaseUpdateMirror: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{mirror.name=projects/*/locations/*/instances/*/mirrors/*}", + "body": "mirror", + }, + ] + return http_options + class _BaseGetLocation: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -236,6 +410,64 @@ def _get_http_options(): ] return http_options + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/instances/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/instances/*/directoryPolicies/*}:getIamPolicy", + }, + ] + return http_options + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/instances/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/instances/*/directoryPolicies/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/instances/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/instances/*/directoryPolicies/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + class _BaseCancelOperation: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-lustre/google/cloud/lustre_v1/types/__init__.py b/packages/google-cloud-lustre/google/cloud/lustre_v1/types/__init__.py index 8cc12f12ec9e..c0b9851fe666 100644 --- a/packages/google-cloud-lustre/google/cloud/lustre_v1/types/__init__.py +++ b/packages/google-cloud-lustre/google/cloud/lustre_v1/types/__init__.py @@ -13,16 +13,39 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from .directory_policy import ( + CreateDirectoryPolicyRequest, + DeleteDirectoryPolicyRequest, + DirectoryPolicy, + GetDirectoryPolicyRequest, + ListDirectoryPoliciesRequest, + ListDirectoryPoliciesResponse, +) from .instance import ( + AccessRulesOptions, CreateInstanceRequest, DeleteInstanceRequest, + DynamicTierOptions, GetInstanceRequest, Instance, ListInstancesRequest, ListInstancesResponse, + MaintenancePolicy, + MaintenanceSchedule, OperationMetadata, + RescheduleMaintenanceRequest, UpdateInstanceRequest, ) +from .mirror import ( + CreateMirrorMetadata, + CreateMirrorRequest, + DeleteMirrorRequest, + GetMirrorRequest, + ListMirrorsRequest, + ListMirrorsResponse, + Mirror, + UpdateMirrorRequest, +) from .transfer import ( ErrorLogEntry, ErrorSummary, @@ -40,14 +63,33 @@ ) __all__ = ( + "CreateDirectoryPolicyRequest", + "DeleteDirectoryPolicyRequest", + "DirectoryPolicy", + "GetDirectoryPolicyRequest", + "ListDirectoryPoliciesRequest", + "ListDirectoryPoliciesResponse", + "AccessRulesOptions", "CreateInstanceRequest", "DeleteInstanceRequest", + "DynamicTierOptions", "GetInstanceRequest", "Instance", "ListInstancesRequest", "ListInstancesResponse", + "MaintenancePolicy", + "MaintenanceSchedule", "OperationMetadata", + "RescheduleMaintenanceRequest", "UpdateInstanceRequest", + "CreateMirrorMetadata", + "CreateMirrorRequest", + "DeleteMirrorRequest", + "GetMirrorRequest", + "ListMirrorsRequest", + "ListMirrorsResponse", + "Mirror", + "UpdateMirrorRequest", "ErrorLogEntry", "ErrorSummary", "ExportDataMetadata", diff --git a/packages/google-cloud-lustre/google/cloud/lustre_v1/types/directory_policy.py b/packages/google-cloud-lustre/google/cloud/lustre_v1/types/directory_policy.py new file mode 100644 index 000000000000..6d013fe310f9 --- /dev/null +++ b/packages/google-cloud-lustre/google/cloud/lustre_v1/types/directory_policy.py @@ -0,0 +1,225 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.lustre.v1", + manifest={ + "DirectoryPolicy", + "CreateDirectoryPolicyRequest", + "DeleteDirectoryPolicyRequest", + "GetDirectoryPolicyRequest", + "ListDirectoryPoliciesRequest", + "ListDirectoryPoliciesResponse", + }, +) + + +class DirectoryPolicy(proto.Message): + r"""A directory policy for a Managed Lustre instance. + + Attributes: + name (str): + Immutable. Identifier. The resource name of the directory + policy. DirectoryPolicy names have the form + ``projects/{project}/locations/{location}/instances/{instance}/directoryPolicies/{id}``. + {id} is user provided. + directory_path (str): + Required. Immutable. The lustre instance + filesystem full path of the directory. It must + start with a slash. e.g. /lustre/testFolder + lustre_project_id (int): + Output only. The lustre project ID assigned for the + directory by the service. This read-only ID can be used to + manage quotas. See more details in + https://docs.cloud.google.com/managed-lustre/docs/file-system-quotas#set_quotas + uid (str): + Output only. Unique ID of the resource. + state (google.cloud.lustre_v1.types.DirectoryPolicy.State): + Output only. The current state of the + directory policy. + """ + + class State(proto.Enum): + r"""State of the directory policy. + + Values: + STATE_UNSPECIFIED (0): + State is unspecified. + CREATING (1): + Directory policy is being created. + ACTIVE (2): + Directory policy is active and ready to be + used. + DELETING (3): + Directory policy is being deleted. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + DELETING = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + directory_path: str = proto.Field( + proto.STRING, + number=2, + ) + lustre_project_id: int = proto.Field( + proto.INT64, + number=3, + ) + uid: str = proto.Field( + proto.STRING, + number=4, + ) + state: State = proto.Field( + proto.ENUM, + number=5, + enum=State, + ) + + +class CreateDirectoryPolicyRequest(proto.Message): + r"""Request message for CreateDirectoryPolicy. + + Attributes: + parent (str): + Required. The parent instance. It must be in the format of + ``projects/{project}/locations/{location}/instances/{instance}``. + directory_policy_id (str): + Required. The ID for the DirectoryPolicy to + create. + directory_policy (google.cloud.lustre_v1.types.DirectoryPolicy): + Required. The directory policy to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + directory_policy_id: str = proto.Field( + proto.STRING, + number=2, + ) + directory_policy: "DirectoryPolicy" = proto.Field( + proto.MESSAGE, + number=3, + message="DirectoryPolicy", + ) + + +class DeleteDirectoryPolicyRequest(proto.Message): + r"""Request message for DeleteDirectoryPolicy. + + Attributes: + name (str): + Required. The resource name of the directory policy. + DirectoryPolicy names have the form + ``projects/{project}/locations/{location}/instances/{instance}/directoryPolicies/{id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetDirectoryPolicyRequest(proto.Message): + r"""Request message for GetDirectoryPolicy. + + Attributes: + name (str): + Required. The resource name of the directory policy. + DirectoryPolicy names have the form + ``projects/{project}/locations/{location}/instances/{instance}/directoryPolicies/{id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDirectoryPoliciesRequest(proto.Message): + r"""Request message for ListDirectoryPolicies. + + Attributes: + parent (str): + Required. The parent instance. It must be in the format of + ``projects/{project}/locations/{location}/instances/{instance}``. + page_size (int): + Optional. Requested page size. Server might + return fewer items than requested. If + unspecified, the server will pick an appropriate + default. The maximum value is 1000; values above + 1000 will be coerced to 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListDirectoryPolicies`` call. Provide this to retrieve the + subsequent page. When paginating, all other parameters + provided to ``ListDirectoryPolicies`` must match the call + that provided the page token. + """ + + 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 ListDirectoryPoliciesResponse(proto.Message): + r"""Response message for ListDirectoryPolicies. + + Attributes: + directory_policies (MutableSequence[google.cloud.lustre_v1.types.DirectoryPolicy]): + The list of DirectoryPolicies. + next_page_token (str): + A token identifying a page of results the + server should return. + """ + + @property + def raw_page(self): + return self + + directory_policies: MutableSequence["DirectoryPolicy"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="DirectoryPolicy", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-lustre/google/cloud/lustre_v1/types/instance.py b/packages/google-cloud-lustre/google/cloud/lustre_v1/types/instance.py index 6db1c38bec83..280e446a3d3a 100644 --- a/packages/google-cloud-lustre/google/cloud/lustre_v1/types/instance.py +++ b/packages/google-cloud-lustre/google/cloud/lustre_v1/types/instance.py @@ -19,12 +19,17 @@ import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.type.date_pb2 as date_pb2 # type: ignore +import google.type.dayofweek_pb2 as dayofweek_pb2 # type: ignore +import google.type.timeofday_pb2 as timeofday_pb2 # type: ignore import proto # type: ignore __protobuf__ = proto.module( package="google.cloud.lustre.v1", manifest={ "Instance", + "DynamicTierOptions", + "AccessRulesOptions", "ListInstancesRequest", "ListInstancesResponse", "GetInstanceRequest", @@ -32,6 +37,9 @@ "UpdateInstanceRequest", "DeleteInstanceRequest", "OperationMetadata", + "MaintenancePolicy", + "MaintenanceSchedule", + "RescheduleMaintenanceRequest", }, ) @@ -39,6 +47,8 @@ class Instance(proto.Message): r"""A Managed Lustre instance. + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: name (str): Identifier. The name of the instance. @@ -50,8 +60,11 @@ class Instance(proto.Message): contain letters and numbers. capacity_gib (int): Required. The storage capacity of the instance in gibibytes - (GiB). Allowed values are from ``18000`` to ``954000``, in - increments of 9000. + (GiB). Allowed values depend on the + ``perUnitStorageThroughput``. See `Performance + tiers `__ + for specific minimums, maximums, and step sizes for each + performance tier. network (str): Required. Immutable. The full name of the VPC network to which the instance is connected. Must be in the format @@ -73,13 +86,68 @@ class Instance(proto.Message): labels (MutableMapping[str, str]): Optional. Labels as key value pairs. per_unit_storage_throughput (int): - Required. The throughput of the instance in - MB/s/TiB. Valid values are 125, 250, 500, 1000. + Optional. The throughput of the instance in MBps per TiB. + Valid values are 0, 125, 250, 500, 1000. See `Performance + tiers `__ + for more information. + + If the instance is using the Dynamic tier, this field must + not be set or must be set to zero. gke_support_enabled (bool): - Optional. Indicates whether you want to - enable support for GKE clients. By default, GKE - clients are not supported. Deprecated. No longer - required for GKE instance creation. + Optional. Deprecated: No longer required for + GKE instance creation. Indicates whether you + want to enable support for GKE clients. By + default, GKE clients are not supported. + kms_key (str): + Optional. Immutable. The Cloud KMS key name to use for data + encryption. If not set, the instance will use Google-managed + encryption keys. If set, the instance will use + customer-managed encryption keys. The key must be in the + same region as the instance. The key format is: + projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{key} + state_reason (str): + Output only. The reason why the instance is + in a certain state (e.g. SUSPENDED). + placement_policy (str): + Optional. The placement policy name for the instance in the + format of + projects/{project}/locations/{location}/resourcePolicies/{resource_policy} + access_rules_options (google.cloud.lustre_v1.types.AccessRulesOptions): + Optional. The access rules options for the + instance. + uid (str): + Output only. Unique ID of the resource. + This is unrelated to the access rules which + allow specifying the root squash uid. + maintenance_policy (google.cloud.lustre_v1.types.MaintenancePolicy): + Optional. The maintenance policy for the + instance to determine when to allow or exclude + the instance from maintenance updates. + upcoming_maintenance_schedule (google.cloud.lustre_v1.types.MaintenanceSchedule): + Output only. Date and time of upcoming + maintenance for the instance, if a maintenance + policy is set. + dynamic_tier_options (google.cloud.lustre_v1.types.DynamicTierOptions): + Optional. Immutable. Specifies whether the instance is on + the Dynamic tier. See `Performance + tiers `__ + for more information. + available_version (str): + Output only. The available version that this instance can be + upgraded to. Format: ``Lustre_YYYYMMDD.NN_pXX`` + + This field is a member of `oneof`_ ``_available_version``. + target_version (str): + Optional. The target version of the instance. Setting this + field triggers a self-service update to the specified + version. Format: ``Lustre_YYYYMMDD.NN_pXX`` or ``latest`` + + This field is a member of `oneof`_ ``_target_version``. + effective_version (str): + Output only. The effective version of the instance. Format: + ``Lustre_YYYYMMDD.NN_pXX`` + + This field is a member of `oneof`_ ``_effective_version``. """ class State(proto.Enum): @@ -103,6 +171,10 @@ class State(proto.Enum): The instance is stopped. UPDATING (7): The instance is being updated. + SUSPENDED (8): + The instance is suspended due to an issue related to Cloud + KMS. The details are available in + [state_reason][google.cloud.lustre.v1.Instance.state_reason]. """ STATE_UNSPECIFIED = 0 @@ -113,6 +185,7 @@ class State(proto.Enum): REPAIRING = 5 STOPPED = 6 UPDATING = 7 + SUSPENDED = 8 name: str = proto.Field( proto.STRING, @@ -166,6 +239,212 @@ class State(proto.Enum): proto.BOOL, number=12, ) + kms_key: str = proto.Field( + proto.STRING, + number=13, + ) + state_reason: str = proto.Field( + proto.STRING, + number=14, + ) + placement_policy: str = proto.Field( + proto.STRING, + number=17, + ) + access_rules_options: "AccessRulesOptions" = proto.Field( + proto.MESSAGE, + number=18, + message="AccessRulesOptions", + ) + uid: str = proto.Field( + proto.STRING, + number=19, + ) + maintenance_policy: "MaintenancePolicy" = proto.Field( + proto.MESSAGE, + number=20, + message="MaintenancePolicy", + ) + upcoming_maintenance_schedule: "MaintenanceSchedule" = proto.Field( + proto.MESSAGE, + number=21, + message="MaintenanceSchedule", + ) + dynamic_tier_options: "DynamicTierOptions" = proto.Field( + proto.MESSAGE, + number=24, + message="DynamicTierOptions", + ) + available_version: str = proto.Field( + proto.STRING, + number=33, + optional=True, + ) + target_version: str = proto.Field( + proto.STRING, + number=34, + optional=True, + ) + effective_version: str = proto.Field( + proto.STRING, + number=35, + optional=True, + ) + + +class DynamicTierOptions(proto.Message): + r"""Dynamic tier options for a Managed Lustre instance. + + Attributes: + mode (google.cloud.lustre_v1.types.DynamicTierOptions.Mode): + Required. Immutable. The dynamic tier mode of + the instance. + """ + + class Mode(proto.Enum): + r"""Specifies the Dynamic performance tier for the instance. + + If this field is set to ``DEFAULT_CACHE``, + ``per_unit_storage_throughput`` must not be set or must be set to + zero. + + Values: + MODE_UNSPECIFIED (0): + Unspecified dynamic tier mode. + DISABLED (1): + The dynamic tier is explicitly disabled. + DEFAULT_CACHE (2): + The dynamic tier is enabled. + """ + + MODE_UNSPECIFIED = 0 + DISABLED = 1 + DEFAULT_CACHE = 2 + + mode: Mode = proto.Field( + proto.ENUM, + number=1, + enum=Mode, + ) + + +class AccessRulesOptions(proto.Message): + r"""IP-based access rules for the Managed Lustre instance. These + options define the root user squash configuration. + + Attributes: + access_rules (MutableSequence[google.cloud.lustre_v1.types.AccessRulesOptions.AccessRule]): + Optional. The access rules for the instance. + default_squash_mode (google.cloud.lustre_v1.types.AccessRulesOptions.SquashMode): + Required. The squash mode for the default + access rule. + default_squash_uid (int): + Optional. The user squash UID for the default + access rule. This user squash UID applies to all + root users connecting from clients that are not + matched by any of the access rules. If not set, + the default is 0 (no UID squash). + default_squash_gid (int): + Optional. The user squash GID for the default + access rule. This user squash GID applies to all + root users connecting from clients that are not + matched by any of the access rules. If not set, + the default is 0 (no GID squash). + """ + + class SquashMode(proto.Enum): + r"""Squash mode for an access rule. + + Values: + SQUASH_MODE_UNSPECIFIED (0): + Unspecified squash mode. + NO_SQUASH (1): + Squash is disabled. + + If set inside an + [AccessRule][google.cloud.lustre.v1.AccessRulesOptions.AccessRule], + root users matching the [ip_ranges][AccessRule.ip_ranges] + are not squashed. + + If set as the + [default_squash_mode][google.cloud.lustre.v1.AccessRulesOptions.default_squash_mode], + root squash is disabled for this instance. + + If the default squash mode is ``NO_SQUASH``, do not set the + [default_squash_uid][google.cloud.lustre.v1.AccessRulesOptions.default_squash_uid] + or + [default_squash_gid][google.cloud.lustre.v1.AccessRulesOptions.default_squash_gid], + or an ``invalid argument`` error is returned. + ROOT_SQUASH (2): + Root user squash is enabled. + + Not supported inside an + [AccessRule][google.cloud.lustre.v1.AccessRulesOptions.AccessRule]. + + If set as the + [default_squash_mode][google.cloud.lustre.v1.AccessRulesOptions.default_squash_mode], + root users not matching any of the + [access_rules][google.cloud.lustre.v1.AccessRulesOptions.access_rules] + are squashed to the + [default_squash_uid][google.cloud.lustre.v1.AccessRulesOptions.default_squash_uid] + and + [default_squash_gid][google.cloud.lustre.v1.AccessRulesOptions.default_squash_gid]. + """ + + SQUASH_MODE_UNSPECIFIED = 0 + NO_SQUASH = 1 + ROOT_SQUASH = 2 + + class AccessRule(proto.Message): + r"""A single policy group with IP-based access rules for the + Managed Lustre instance. + + Attributes: + name (str): + Required. The name of the access rule policy group. Must be + 16 characters or less and include only alphanumeric + characters or '\_'. + ip_address_ranges (MutableSequence[str]): + Required. The IP address ranges to which to apply this + access rule. Accepts non-overlapping CIDR ranges (e.g., + ``192.168.1.0/24``) and IP addresses (e.g., + ``192.168.1.0``). + squash_mode (google.cloud.lustre_v1.types.AccessRulesOptions.SquashMode): + Required. Squash mode for the access rule. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + ip_address_ranges: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + squash_mode: "AccessRulesOptions.SquashMode" = proto.Field( + proto.ENUM, + number=6, + enum="AccessRulesOptions.SquashMode", + ) + + access_rules: MutableSequence[AccessRule] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=AccessRule, + ) + default_squash_mode: SquashMode = proto.Field( + proto.ENUM, + number=2, + enum=SquashMode, + ) + default_squash_uid: int = proto.Field( + proto.INT32, + number=3, + ) + default_squash_gid: int = proto.Field( + proto.INT32, + number=4, + ) class ListInstancesRequest(proto.Message): @@ -404,6 +683,11 @@ class DeleteInstanceRequest(proto.Message): The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). + force (bool): + Optional. If set to true, any sub-resources + from this instance will also be deleted. + Otherwise, the request will only work if the + instance has no sub-resources. """ name: str = proto.Field( @@ -414,6 +698,10 @@ class DeleteInstanceRequest(proto.Message): proto.STRING, number=2, ) + force: bool = proto.Field( + proto.BOOL, + number=3, + ) class OperationMetadata(proto.Message): @@ -478,4 +766,197 @@ class OperationMetadata(proto.Message): ) +class MaintenancePolicy(proto.Message): + r"""Defines a maintenance policy for a resource. + + Attributes: + weekly_maintenance_windows (MutableSequence[google.cloud.lustre_v1.types.MaintenancePolicy.WeeklyMaintenanceWindow]): + Required. The weekly maintenance windows for + the instance. Currently limited to 1 window. + maintenance_exclusion_window (MutableSequence[google.cloud.lustre_v1.types.MaintenancePolicy.MaintenanceExclusionWindow]): + Optional. The exclusion windows for the + instance. Currently limited to 1 window. + """ + + class WeeklyMaintenanceWindow(proto.Message): + r"""Weekly time window in which maintenance updates may occur. + Duration of the window is currently fixed at 1 hour. Time zone + is UTC. + + Attributes: + day_of_week (google.type.dayofweek_pb2.DayOfWeek): + Required. Day of the week for the maintenance + window. + start_time (google.type.timeofday_pb2.TimeOfDay): + Required. Start time of the maintenance + window in UTC time zone. + """ + + day_of_week: dayofweek_pb2.DayOfWeek = proto.Field( + proto.ENUM, + number=1, + enum=dayofweek_pb2.DayOfWeek, + ) + start_time: timeofday_pb2.TimeOfDay = proto.Field( + proto.MESSAGE, + number=2, + message=timeofday_pb2.TimeOfDay, + ) + + class MaintenanceExclusionWindow(proto.Message): + r"""Exclusion period when maintenance updates should not occur. An + exclusion window can be in either of the following two formats: + + - Non-recurring : A full date, with non-zero year, month and day + values. + - Recurring : A month and day value, with a zero year. Time zone is + UTC. + + Attributes: + start_date (google.type.date_pb2.Date): + Required. Start date of the exclusion period + in UTC time zone. This date is inclusive. + end_date (google.type.date_pb2.Date): + Required. End date of the exclusion period in + UTC time zone. This date is inclusive. + time (google.type.timeofday_pb2.TimeOfDay): + Required. Time in UTC when the exclusion window starts on + start_date and ends on end_date. This can be: + + - Full time OR + - All zeros for 00:00:00 UTC + """ + + start_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=1, + message=date_pb2.Date, + ) + end_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=2, + message=date_pb2.Date, + ) + time: timeofday_pb2.TimeOfDay = proto.Field( + proto.MESSAGE, + number=3, + message=timeofday_pb2.TimeOfDay, + ) + + weekly_maintenance_windows: MutableSequence[WeeklyMaintenanceWindow] = ( + proto.RepeatedField( + proto.MESSAGE, + number=3, + message=WeeklyMaintenanceWindow, + ) + ) + maintenance_exclusion_window: MutableSequence[MaintenanceExclusionWindow] = ( + proto.RepeatedField( + proto.MESSAGE, + number=4, + message=MaintenanceExclusionWindow, + ) + ) + + +class MaintenanceSchedule(proto.Message): + r"""Represents a scheduled maintenance event. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The scheduled start time for the + maintenance. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The scheduled end time for the + maintenance. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class RescheduleMaintenanceRequest(proto.Message): + r"""Message for requesting to reschedule a maintenance event for + a specific instance. + + Attributes: + name (str): + Required. Format: + + projects/{project}/locations/{location}/instances/{instance} + reschedule (google.cloud.lustre_v1.types.RescheduleMaintenanceRequest.Reschedule): + Required. The desired reschedule settings. + request_id (str): + Optional. A unique identifier for this request. A random + UUID is recommended. This request is only idempotent if a + ``request_id`` is provided. + """ + + class RescheduleType(proto.Enum): + r"""The type of rescheduling event. More reschedule types may be + added in the future. + + Values: + RESCHEDULE_TYPE_UNSPECIFIED (0): + Unspecified schedule type. + IMMEDIATE (1): + Apply update immediately + NEXT_AVAILABLE_WINDOW (2): + Reschedule to the next available window. + BY_TIME (3): + Reschedule to a specific time. + """ + + RESCHEDULE_TYPE_UNSPECIFIED = 0 + IMMEDIATE = 1 + NEXT_AVAILABLE_WINDOW = 2 + BY_TIME = 3 + + class Reschedule(proto.Message): + r"""The desired reschedule settings. + + Attributes: + reschedule_type (google.cloud.lustre_v1.types.RescheduleMaintenanceRequest.RescheduleType): + Required. The type of rescheduling. + schedule_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Required if reschedule_type is BY_TIME. Timestamp + when the maintenance shall be rescheduled to. This time must + be within 28 days of the original scheduled maintenance + start time. + """ + + reschedule_type: "RescheduleMaintenanceRequest.RescheduleType" = proto.Field( + proto.ENUM, + number=1, + enum="RescheduleMaintenanceRequest.RescheduleType", + ) + schedule_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + reschedule: Reschedule = proto.Field( + proto.MESSAGE, + number=2, + message=Reschedule, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-lustre/google/cloud/lustre_v1/types/mirror.py b/packages/google-cloud-lustre/google/cloud/lustre_v1/types/mirror.py new file mode 100644 index 000000000000..82c0f3fb8682 --- /dev/null +++ b/packages/google-cloud-lustre/google/cloud/lustre_v1/types/mirror.py @@ -0,0 +1,488 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.lustre_v1.types import transfer + +__protobuf__ = proto.module( + package="google.cloud.lustre.v1", + manifest={ + "Mirror", + "CreateMirrorRequest", + "UpdateMirrorRequest", + "DeleteMirrorRequest", + "GetMirrorRequest", + "ListMirrorsRequest", + "ListMirrorsResponse", + "CreateMirrorMetadata", + }, +) + + +class Mirror(proto.Message): + r"""Represents a Cloud Storage mirror. + + Attributes: + name (str): + Identifier. Name of the mirror. Format: + ``projects/{project}/locations/{location}/instances/{instance}/mirrors/{mirror}`` + gcs_path (google.cloud.lustre_v1.types.GcsPath): + Required. Immutable. The URI to a Cloud Storage bucket, or a + path within a bucket, using the format + ``gs://{BUCKET_NAME}/{OPTIONAL_PATH}/``. If a path inside + the bucket is specified, it must end with a forward slash + (``/``). + lustre_path (google.cloud.lustre_v1.types.LustrePath): + Required. Immutable. The Managed Lustre directory to mirror + to. Must be an absolute path starting with ``/``, for + example ``/data`` or ``/data/subdir``. Defaults to the root + directory, ``/``. If the specified directory doesn't exist, + it is created. + direction (google.cloud.lustre_v1.types.Mirror.Direction): + Required. Immutable. Represents the direction + of the mirror. + deleted_files_retained (bool): + Optional. If ``true``, files are not deleted from Managed + Lustre when the source files are deleted from Cloud Storage. + Default is ``false``. + description (str): + Optional. Description of the mirror. + labels (MutableMapping[str, str]): + Optional. Labels to apply to the mirror. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Create time stamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. [Output only] Update time stamp. + uid (str): + Output only. Unique ID of the resource. + state (google.cloud.lustre_v1.types.Mirror.State): + Output only. [Output only] The current state of the mirror. + """ + + class Direction(proto.Enum): + r"""Represents the direction of the mirror. + This enum expects to be extended in future with new mirror + types. + + Values: + DIRECTION_UNSPECIFIED (0): + Invalid value. + FROM_CLOUD_STORAGE (1): + Mirror from Cloud Storage to Lustre. + """ + + DIRECTION_UNSPECIFIED = 0 + FROM_CLOUD_STORAGE = 1 + + class State(proto.Enum): + r"""State of the mirror. + + Values: + STATE_UNSPECIFIED (0): + State is unspecified. + CREATING (1): + The mirror resource is being created. + INITIAL_SYNC (2): + The initial sync is copying existing objects + from Cloud Storage. + DELETING (3): + The mirror is being deleted. + ACTIVE (4): + The mirror is synchronizing changes as they + occur. + SUSPENDED (5): + Synchronization is paused because the file + system is close to capacity. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + INITIAL_SYNC = 2 + DELETING = 3 + ACTIVE = 4 + SUSPENDED = 5 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + gcs_path: transfer.GcsPath = proto.Field( + proto.MESSAGE, + number=3, + message=transfer.GcsPath, + ) + lustre_path: transfer.LustrePath = proto.Field( + proto.MESSAGE, + number=4, + message=transfer.LustrePath, + ) + direction: Direction = proto.Field( + proto.ENUM, + number=5, + enum=Direction, + ) + deleted_files_retained: bool = proto.Field( + proto.BOOL, + number=6, + ) + description: str = proto.Field( + proto.STRING, + number=7, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + uid: str = proto.Field( + proto.STRING, + number=11, + ) + state: State = proto.Field( + proto.ENUM, + number=12, + enum=State, + ) + + +class CreateMirrorRequest(proto.Message): + r"""Request for CreateMirror. + + Attributes: + parent (str): + Required. Parent instance resource where the mirror will be + created, in the format: + ``projects/{project}/locations/{location}/instances/{instance}`` + mirror_id (str): + Required. The ID to use for the mirror. + + - Must contain only lowercase letters, numbers, and hyphens. + - Must start with a letter. + - Must be between 1-63 characters. + - Must end with a number or a letter. + + The ID cannot be changed after the mirror is created. + mirror (google.cloud.lustre_v1.types.Mirror): + Required. The mirror to create. + request_id (str): + Optional. The unique ID to identify requests. Specify a + unique request ID so that if you must retry your request, + the server will know to ignore the request if it has already + been completed. The server guarantees that a request doesn't + result in creation of duplicate mirrors for at least 60 + minutes. + + For example, consider a situation where you make an initial + request and the request times out. If you make the request + again with the same request ID, the server can check if + original operation with the same request ID was received, + and if so, will ignore the second request. This prevents + clients from accidentally creating duplicate mirrors. + + The request ID must be a valid UUID version 4 with the + exception that zero UUID is not supported + (``00000000-0000-0000-0000-000000000000``). This request is + only idempotent if a ``request_id`` is provided. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + mirror_id: str = proto.Field( + proto.STRING, + number=2, + ) + mirror: "Mirror" = proto.Field( + proto.MESSAGE, + number=3, + message="Mirror", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateMirrorRequest(proto.Message): + r"""Request for UpdateMirror. + + Attributes: + mirror (google.cloud.lustre_v1.types.Mirror): + Required. Mirror to update. The mirror's ``name`` field is + used to identify the mirror to update, in the format: + ``projects/{project}/locations/{location}/instances/{instance}/mirrors/{mirror}`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Fields specified in the update_mask are relative + to the resource, not the full request. A field will be + overwritten if it is in the mask. If no mask is provided + then all fields present in the request are overwritten. + request_id (str): + Optional. The unique ID to identify requests. Specify a + unique request ID so that if you must retry your request, + the server will know to ignore the request if it has already + been completed. The server guarantees that a request doesn't + result in the same update request being executed for at + least 60 minutes. + + For example, consider a situation where you make an initial + request and the request times out. If you make the request + again with the same request ID, the server can check if + original operation with the same request ID was received, + and if so, will ignore the second request. + + The request ID must be a valid UUID version 4 with the + exception that zero UUID is not supported + (``00000000-0000-0000-0000-000000000000``). This request is + only idempotent if a ``request_id`` is provided. + """ + + mirror: "Mirror" = proto.Field( + proto.MESSAGE, + number=1, + message="Mirror", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteMirrorRequest(proto.Message): + r"""Request for DeleteMirror. + + Attributes: + name (str): + Required. Name of the mirror to delete, in the format: + ``projects/{project}/locations/{location}/instances/{instance}/mirrors/{mirror}`` + request_id (str): + Optional. The unique ID to identify requests. Specify a + unique request ID so that if you must retry your request, + the server will know to ignore the request if it has already + been completed. The server guarantees that a request doesn't + result in the same delete request being executed for at + least 60 minutes. + + For example, consider a situation where you make an initial + request and the request times out. If you make the request + again with the same request ID, the server can check if + original operation with the same request ID was received, + and if so, will ignore the second request. + + The request ID must be a valid UUID version 4 with the + exception that zero UUID is not supported + (``00000000-0000-0000-0000-000000000000``). This request is + only idempotent if a ``request_id`` is provided. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetMirrorRequest(proto.Message): + r"""Request for GetMirror. + + Attributes: + name (str): + Required. Name of the mirror to retrieve, in the format: + ``projects/{project}/locations/{location}/instances/{instance}/mirrors/{mirror}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListMirrorsRequest(proto.Message): + r"""Request for ListMirrors. + + Attributes: + parent (str): + Required. Parent instance resource where the mirrors will be + listed, in the format: + ``projects/{project}/locations/{location}/instances/{instance}`` + page_size (int): + Optional. Requested page size. The server + might return fewer items than requested. If + unspecified, the default page size is 10. The + maximum value is 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListMirrors`` call. Provide this to retrieve the + subsequent page. When paginating, all other parameters + provided to ``ListMirrors`` must match the call that + provided the page token. + order_by (str): + Optional. Desired order of results. + filter (str): + Optional. Filtering results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + order_by: str = proto.Field( + proto.STRING, + number=4, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListMirrorsResponse(proto.Message): + r"""Response for ListMirrors. + + Attributes: + mirrors (MutableSequence[google.cloud.lustre_v1.types.Mirror]): + List of mirrors on the instance. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Unordered list. Locations that could not be + reached. + """ + + @property + def raw_page(self): + return self + + mirrors: MutableSequence["Mirror"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Mirror", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateMirrorMetadata(proto.Message): + r"""Metadata of the create mirror operation. + + Attributes: + operation_metadata (google.cloud.lustre_v1.types.TransferOperationMetadata): + Data transfer operation metadata. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time 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. Operations that have + successfully been cancelled have + [google.longrunning.Operation.error][google.longrunning.Operation.error] + value with a + [google.rpc.Status.code][google.rpc.Status.code] of 1, + corresponding to ``Code.CANCELLED``. + api_version (str): + Output only. API version used to start the + operation. + """ + + operation_metadata: transfer.TransferOperationMetadata = proto.Field( + proto.MESSAGE, + number=1, + message=transfer.TransferOperationMetadata, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + target: str = proto.Field( + proto.STRING, + number=4, + ) + verb: str = proto.Field( + proto.STRING, + number=5, + ) + status_message: str = proto.Field( + proto.STRING, + number=6, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=7, + ) + api_version: str = proto.Field( + proto.STRING, + number=8, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-lustre/google/cloud/lustre_v1/types/transfer.py b/packages/google-cloud-lustre/google/cloud/lustre_v1/types/transfer.py index d778b068113c..68e7e7da9c70 100644 --- a/packages/google-cloud-lustre/google/cloud/lustre_v1/types/transfer.py +++ b/packages/google-cloud-lustre/google/cloud/lustre_v1/types/transfer.py @@ -81,10 +81,15 @@ class ImportDataRequest(proto.Message): request_id (str): Optional. UUID to identify requests. service_account (str): - Optional. User-specified service account used - to perform the transfer. If unspecified, the - default Managed Lustre service agent will be - used. + Optional. User-specified service account used to perform the + transfer. If unspecified, the default Managed Lustre service + agent will be used. + + Use one of the following formats: + + - ``{EMAIL_ADDRESS_OR_UNIQUE_ID}`` + - ``projects/{PROJECT_ID}/serviceAccounts/{EMAIL_ADDRESS_OR_UNIQUE_ID}`` + - ``projects/-/serviceAccounts/{EMAIL_ADDRESS_OR_UNIQUE_ID}`` """ gcs_path: "GcsPath" = proto.Field( @@ -139,9 +144,15 @@ class ExportDataRequest(proto.Message): request_id (str): Optional. UUID to identify requests. service_account (str): - Optional. User-specified service account used - to perform the transfer. If unspecified, the - Managed Lustre service agent is used. + Optional. User-specified service account used to perform the + transfer. If unspecified, the Managed Lustre service agent + is used. + + Use one of the following formats: + + - ``{EMAIL_ADDRESS_OR_UNIQUE_ID}`` + - ``projects/{PROJECT_ID}/serviceAccounts/{EMAIL_ADDRESS_OR_UNIQUE_ID}`` + - ``projects/-/serviceAccounts/{EMAIL_ADDRESS_OR_UNIQUE_ID}`` """ lustre_path: "LustrePath" = proto.Field( diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_directory_policy_async.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_directory_policy_async.py new file mode 100644 index 000000000000..75ede76db704 --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_directory_policy_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDirectoryPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_CreateDirectoryPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +async def sample_create_directory_policy(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + directory_policy = lustre_v1.DirectoryPolicy() + directory_policy.directory_path = "directory_path_value" + + request = lustre_v1.CreateDirectoryPolicyRequest( + parent="parent_value", + directory_policy_id="directory_policy_id_value", + directory_policy=directory_policy, + ) + + # Make the request + operation = await client.create_directory_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END lustre_v1_generated_Lustre_CreateDirectoryPolicy_async] diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_directory_policy_sync.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_directory_policy_sync.py new file mode 100644 index 000000000000..6c63f04d0107 --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_directory_policy_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDirectoryPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_CreateDirectoryPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +def sample_create_directory_policy(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + directory_policy = lustre_v1.DirectoryPolicy() + directory_policy.directory_path = "directory_path_value" + + request = lustre_v1.CreateDirectoryPolicyRequest( + parent="parent_value", + directory_policy_id="directory_policy_id_value", + directory_policy=directory_policy, + ) + + # Make the request + operation = client.create_directory_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END lustre_v1_generated_Lustre_CreateDirectoryPolicy_sync] diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_instance_async.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_instance_async.py index edd4b4a4c501..7f4cde56d77b 100644 --- a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_instance_async.py +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_instance_async.py @@ -43,7 +43,6 @@ async def sample_create_instance(): instance.filesystem = "filesystem_value" instance.capacity_gib = 1247 instance.network = "network_value" - instance.per_unit_storage_throughput = 2931 request = lustre_v1.CreateInstanceRequest( parent="parent_value", diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_instance_sync.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_instance_sync.py index f6b07690c8e4..610869adf91f 100644 --- a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_instance_sync.py +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_instance_sync.py @@ -43,7 +43,6 @@ def sample_create_instance(): instance.filesystem = "filesystem_value" instance.capacity_gib = 1247 instance.network = "network_value" - instance.per_unit_storage_throughput = 2931 request = lustre_v1.CreateInstanceRequest( parent="parent_value", diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_mirror_async.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_mirror_async.py new file mode 100644 index 000000000000..7b37ac3fba0d --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_mirror_async.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMirror +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_CreateMirror_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +async def sample_create_mirror(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + mirror = lustre_v1.Mirror() + mirror.gcs_path.uri = "uri_value" + mirror.direction = "FROM_CLOUD_STORAGE" + + request = lustre_v1.CreateMirrorRequest( + parent="parent_value", + mirror_id="mirror_id_value", + mirror=mirror, + ) + + # Make the request + operation = await client.create_mirror(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END lustre_v1_generated_Lustre_CreateMirror_async] diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_mirror_sync.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_mirror_sync.py new file mode 100644 index 000000000000..da75133e5a21 --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_create_mirror_sync.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMirror +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_CreateMirror_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +def sample_create_mirror(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + mirror = lustre_v1.Mirror() + mirror.gcs_path.uri = "uri_value" + mirror.direction = "FROM_CLOUD_STORAGE" + + request = lustre_v1.CreateMirrorRequest( + parent="parent_value", + mirror_id="mirror_id_value", + mirror=mirror, + ) + + # Make the request + operation = client.create_mirror(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END lustre_v1_generated_Lustre_CreateMirror_sync] diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_delete_directory_policy_async.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_delete_directory_policy_async.py new file mode 100644 index 000000000000..ac966fee038a --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_delete_directory_policy_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDirectoryPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_DeleteDirectoryPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +async def sample_delete_directory_policy(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + request = lustre_v1.DeleteDirectoryPolicyRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_directory_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END lustre_v1_generated_Lustre_DeleteDirectoryPolicy_async] diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_delete_directory_policy_sync.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_delete_directory_policy_sync.py new file mode 100644 index 000000000000..2b088870f7c4 --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_delete_directory_policy_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDirectoryPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_DeleteDirectoryPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +def sample_delete_directory_policy(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + request = lustre_v1.DeleteDirectoryPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_directory_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END lustre_v1_generated_Lustre_DeleteDirectoryPolicy_sync] diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_delete_mirror_async.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_delete_mirror_async.py new file mode 100644 index 000000000000..8f54bb2e3507 --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_delete_mirror_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteMirror +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_DeleteMirror_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +async def sample_delete_mirror(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + request = lustre_v1.DeleteMirrorRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_mirror(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END lustre_v1_generated_Lustre_DeleteMirror_async] diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_delete_mirror_sync.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_delete_mirror_sync.py new file mode 100644 index 000000000000..22149cd33162 --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_delete_mirror_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteMirror +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_DeleteMirror_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +def sample_delete_mirror(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + request = lustre_v1.DeleteMirrorRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_mirror(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END lustre_v1_generated_Lustre_DeleteMirror_sync] diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_get_directory_policy_async.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_get_directory_policy_async.py new file mode 100644 index 000000000000..2b60ddadd937 --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_get_directory_policy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDirectoryPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_GetDirectoryPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +async def sample_get_directory_policy(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + request = lustre_v1.GetDirectoryPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_directory_policy(request=request) + + # Handle the response + print(response) + + +# [END lustre_v1_generated_Lustre_GetDirectoryPolicy_async] diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_get_directory_policy_sync.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_get_directory_policy_sync.py new file mode 100644 index 000000000000..b567e784eec1 --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_get_directory_policy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDirectoryPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_GetDirectoryPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +def sample_get_directory_policy(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + request = lustre_v1.GetDirectoryPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_directory_policy(request=request) + + # Handle the response + print(response) + + +# [END lustre_v1_generated_Lustre_GetDirectoryPolicy_sync] diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_get_mirror_async.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_get_mirror_async.py new file mode 100644 index 000000000000..f306b3b23e94 --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_get_mirror_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMirror +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_GetMirror_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +async def sample_get_mirror(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + request = lustre_v1.GetMirrorRequest( + name="name_value", + ) + + # Make the request + response = await client.get_mirror(request=request) + + # Handle the response + print(response) + + +# [END lustre_v1_generated_Lustre_GetMirror_async] diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_get_mirror_sync.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_get_mirror_sync.py new file mode 100644 index 000000000000..fa1a68d7bb0d --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_get_mirror_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMirror +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_GetMirror_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +def sample_get_mirror(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + request = lustre_v1.GetMirrorRequest( + name="name_value", + ) + + # Make the request + response = client.get_mirror(request=request) + + # Handle the response + print(response) + + +# [END lustre_v1_generated_Lustre_GetMirror_sync] diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_list_directory_policies_async.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_list_directory_policies_async.py new file mode 100644 index 000000000000..b267c5e84530 --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_list_directory_policies_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDirectoryPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_ListDirectoryPolicies_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +async def sample_list_directory_policies(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + request = lustre_v1.ListDirectoryPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_directory_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END lustre_v1_generated_Lustre_ListDirectoryPolicies_async] diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_list_directory_policies_sync.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_list_directory_policies_sync.py new file mode 100644 index 000000000000..fb61141b1e47 --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_list_directory_policies_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDirectoryPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_ListDirectoryPolicies_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +def sample_list_directory_policies(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + request = lustre_v1.ListDirectoryPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_directory_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END lustre_v1_generated_Lustre_ListDirectoryPolicies_sync] diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_list_mirrors_async.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_list_mirrors_async.py new file mode 100644 index 000000000000..b7a8a6c9369e --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_list_mirrors_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMirrors +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_ListMirrors_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +async def sample_list_mirrors(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + request = lustre_v1.ListMirrorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mirrors(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END lustre_v1_generated_Lustre_ListMirrors_async] diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_list_mirrors_sync.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_list_mirrors_sync.py new file mode 100644 index 000000000000..f0d4e37c1826 --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_list_mirrors_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMirrors +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_ListMirrors_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +def sample_list_mirrors(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + request = lustre_v1.ListMirrorsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mirrors(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END lustre_v1_generated_Lustre_ListMirrors_sync] diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_reschedule_maintenance_async.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_reschedule_maintenance_async.py new file mode 100644 index 000000000000..e8ecca9dc60f --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_reschedule_maintenance_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RescheduleMaintenance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_RescheduleMaintenance_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +async def sample_reschedule_maintenance(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + reschedule = lustre_v1.Reschedule() + reschedule.reschedule_type = "BY_TIME" + + request = lustre_v1.RescheduleMaintenanceRequest( + name="name_value", + reschedule=reschedule, + ) + + # Make the request + operation = await client.reschedule_maintenance(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END lustre_v1_generated_Lustre_RescheduleMaintenance_async] diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_reschedule_maintenance_sync.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_reschedule_maintenance_sync.py new file mode 100644 index 000000000000..fc87fbbcd77e --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_reschedule_maintenance_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RescheduleMaintenance +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_RescheduleMaintenance_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +def sample_reschedule_maintenance(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + reschedule = lustre_v1.Reschedule() + reschedule.reschedule_type = "BY_TIME" + + request = lustre_v1.RescheduleMaintenanceRequest( + name="name_value", + reschedule=reschedule, + ) + + # Make the request + operation = client.reschedule_maintenance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END lustre_v1_generated_Lustre_RescheduleMaintenance_sync] diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_update_instance_async.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_update_instance_async.py index 190b25895288..575e40207d6a 100644 --- a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_update_instance_async.py +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_update_instance_async.py @@ -43,7 +43,6 @@ async def sample_update_instance(): instance.filesystem = "filesystem_value" instance.capacity_gib = 1247 instance.network = "network_value" - instance.per_unit_storage_throughput = 2931 request = lustre_v1.UpdateInstanceRequest( instance=instance, diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_update_instance_sync.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_update_instance_sync.py index a42821a64f09..e44173c41e63 100644 --- a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_update_instance_sync.py +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_update_instance_sync.py @@ -43,7 +43,6 @@ def sample_update_instance(): instance.filesystem = "filesystem_value" instance.capacity_gib = 1247 instance.network = "network_value" - instance.per_unit_storage_throughput = 2931 request = lustre_v1.UpdateInstanceRequest( instance=instance, diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_update_mirror_async.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_update_mirror_async.py new file mode 100644 index 000000000000..c401d1288b09 --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_update_mirror_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMirror +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_UpdateMirror_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +async def sample_update_mirror(): + # Create a client + client = lustre_v1.LustreAsyncClient() + + # Initialize request argument(s) + mirror = lustre_v1.Mirror() + mirror.gcs_path.uri = "uri_value" + mirror.direction = "FROM_CLOUD_STORAGE" + + request = lustre_v1.UpdateMirrorRequest( + mirror=mirror, + ) + + # Make the request + operation = await client.update_mirror(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END lustre_v1_generated_Lustre_UpdateMirror_async] diff --git a/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_update_mirror_sync.py b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_update_mirror_sync.py new file mode 100644 index 000000000000..1fa10904eb43 --- /dev/null +++ b/packages/google-cloud-lustre/samples/generated_samples/lustre_v1_generated_lustre_update_mirror_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMirror +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-lustre + + +# [START lustre_v1_generated_Lustre_UpdateMirror_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import lustre_v1 + + +def sample_update_mirror(): + # Create a client + client = lustre_v1.LustreClient() + + # Initialize request argument(s) + mirror = lustre_v1.Mirror() + mirror.gcs_path.uri = "uri_value" + mirror.direction = "FROM_CLOUD_STORAGE" + + request = lustre_v1.UpdateMirrorRequest( + mirror=mirror, + ) + + # Make the request + operation = client.update_mirror(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END lustre_v1_generated_Lustre_UpdateMirror_sync] diff --git a/packages/google-cloud-lustre/samples/generated_samples/snippet_metadata_google.cloud.lustre.v1.json b/packages/google-cloud-lustre/samples/generated_samples/snippet_metadata_google.cloud.lustre.v1.json index 4360bc6428bd..acd734ee3af4 100644 --- a/packages/google-cloud-lustre/samples/generated_samples/snippet_metadata_google.cloud.lustre.v1.json +++ b/packages/google-cloud-lustre/samples/generated_samples/snippet_metadata_google.cloud.lustre.v1.json @@ -11,6 +11,183 @@ "version": "0.4.1" }, "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.lustre_v1.LustreAsyncClient", + "shortName": "LustreAsyncClient" + }, + "fullName": "google.cloud.lustre_v1.LustreAsyncClient.create_directory_policy", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.CreateDirectoryPolicy", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "CreateDirectoryPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.CreateDirectoryPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "directory_policy", + "type": "google.cloud.lustre_v1.types.DirectoryPolicy" + }, + { + "name": "directory_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_directory_policy" + }, + "description": "Sample for CreateDirectoryPolicy", + "file": "lustre_v1_generated_lustre_create_directory_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_CreateDirectoryPolicy_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "lustre_v1_generated_lustre_create_directory_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.lustre_v1.LustreClient", + "shortName": "LustreClient" + }, + "fullName": "google.cloud.lustre_v1.LustreClient.create_directory_policy", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.CreateDirectoryPolicy", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "CreateDirectoryPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.CreateDirectoryPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "directory_policy", + "type": "google.cloud.lustre_v1.types.DirectoryPolicy" + }, + { + "name": "directory_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_directory_policy" + }, + "description": "Sample for CreateDirectoryPolicy", + "file": "lustre_v1_generated_lustre_create_directory_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_CreateDirectoryPolicy_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "lustre_v1_generated_lustre_create_directory_policy_sync.py" + }, { "canonical": true, "clientMethod": { @@ -68,12 +245,12 @@ "regionTag": "lustre_v1_generated_Lustre_CreateInstance_async", "segments": [ { - "end": 63, + "end": 62, "start": 27, "type": "FULL" }, { - "end": 63, + "end": 62, "start": 27, "type": "SHORT" }, @@ -83,18 +260,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 53, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 60, - "start": 54, + "end": 59, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 64, - "start": 61, + "end": 63, + "start": 60, "type": "RESPONSE_HANDLING" } ], @@ -156,12 +333,12 @@ "regionTag": "lustre_v1_generated_Lustre_CreateInstance_sync", "segments": [ { - "end": 63, + "end": 62, "start": 27, "type": "FULL" }, { - "end": 63, + "end": 62, "start": 27, "type": "SHORT" }, @@ -171,18 +348,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 53, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 60, - "start": 54, + "end": 59, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 64, - "start": 61, + "end": 63, + "start": 60, "type": "RESPONSE_HANDLING" } ], @@ -196,22 +373,30 @@ "fullName": "google.cloud.lustre_v1.LustreAsyncClient", "shortName": "LustreAsyncClient" }, - "fullName": "google.cloud.lustre_v1.LustreAsyncClient.delete_instance", + "fullName": "google.cloud.lustre_v1.LustreAsyncClient.create_mirror", "method": { - "fullName": "google.cloud.lustre.v1.Lustre.DeleteInstance", + "fullName": "google.cloud.lustre.v1.Lustre.CreateMirror", "service": { "fullName": "google.cloud.lustre.v1.Lustre", "shortName": "Lustre" }, - "shortName": "DeleteInstance" + "shortName": "CreateMirror" }, "parameters": [ { "name": "request", - "type": "google.cloud.lustre_v1.types.DeleteInstanceRequest" + "type": "google.cloud.lustre_v1.types.CreateMirrorRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "mirror", + "type": "google.cloud.lustre_v1.types.Mirror" + }, + { + "name": "mirror_id", "type": "str" }, { @@ -228,21 +413,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_instance" + "shortName": "create_mirror" }, - "description": "Sample for DeleteInstance", - "file": "lustre_v1_generated_lustre_delete_instance_async.py", + "description": "Sample for CreateMirror", + "file": "lustre_v1_generated_lustre_create_mirror_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "lustre_v1_generated_Lustre_DeleteInstance_async", + "regionTag": "lustre_v1_generated_Lustre_CreateMirror_async", "segments": [ { - "end": 55, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 61, "start": 27, "type": "SHORT" }, @@ -252,22 +437,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "lustre_v1_generated_lustre_delete_instance_async.py" + "title": "lustre_v1_generated_lustre_create_mirror_async.py" }, { "canonical": true, @@ -276,22 +461,30 @@ "fullName": "google.cloud.lustre_v1.LustreClient", "shortName": "LustreClient" }, - "fullName": "google.cloud.lustre_v1.LustreClient.delete_instance", + "fullName": "google.cloud.lustre_v1.LustreClient.create_mirror", "method": { - "fullName": "google.cloud.lustre.v1.Lustre.DeleteInstance", + "fullName": "google.cloud.lustre.v1.Lustre.CreateMirror", "service": { "fullName": "google.cloud.lustre.v1.Lustre", "shortName": "Lustre" }, - "shortName": "DeleteInstance" + "shortName": "CreateMirror" }, "parameters": [ { "name": "request", - "type": "google.cloud.lustre_v1.types.DeleteInstanceRequest" + "type": "google.cloud.lustre_v1.types.CreateMirrorRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "mirror", + "type": "google.cloud.lustre_v1.types.Mirror" + }, + { + "name": "mirror_id", "type": "str" }, { @@ -308,21 +501,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_instance" + "shortName": "create_mirror" }, - "description": "Sample for DeleteInstance", - "file": "lustre_v1_generated_lustre_delete_instance_sync.py", + "description": "Sample for CreateMirror", + "file": "lustre_v1_generated_lustre_create_mirror_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "lustre_v1_generated_Lustre_DeleteInstance_sync", + "regionTag": "lustre_v1_generated_Lustre_CreateMirror_sync", "segments": [ { - "end": 55, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 61, "start": 27, "type": "SHORT" }, @@ -332,22 +525,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "lustre_v1_generated_lustre_delete_instance_sync.py" + "title": "lustre_v1_generated_lustre_create_mirror_sync.py" }, { "canonical": true, @@ -357,19 +550,1464 @@ "fullName": "google.cloud.lustre_v1.LustreAsyncClient", "shortName": "LustreAsyncClient" }, - "fullName": "google.cloud.lustre_v1.LustreAsyncClient.export_data", + "fullName": "google.cloud.lustre_v1.LustreAsyncClient.delete_directory_policy", "method": { - "fullName": "google.cloud.lustre.v1.Lustre.ExportData", + "fullName": "google.cloud.lustre.v1.Lustre.DeleteDirectoryPolicy", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "DeleteDirectoryPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.DeleteDirectoryPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_directory_policy" + }, + "description": "Sample for DeleteDirectoryPolicy", + "file": "lustre_v1_generated_lustre_delete_directory_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_DeleteDirectoryPolicy_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": "lustre_v1_generated_lustre_delete_directory_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.lustre_v1.LustreClient", + "shortName": "LustreClient" + }, + "fullName": "google.cloud.lustre_v1.LustreClient.delete_directory_policy", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.DeleteDirectoryPolicy", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "DeleteDirectoryPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.DeleteDirectoryPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_directory_policy" + }, + "description": "Sample for DeleteDirectoryPolicy", + "file": "lustre_v1_generated_lustre_delete_directory_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_DeleteDirectoryPolicy_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": "lustre_v1_generated_lustre_delete_directory_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.lustre_v1.LustreAsyncClient", + "shortName": "LustreAsyncClient" + }, + "fullName": "google.cloud.lustre_v1.LustreAsyncClient.delete_instance", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.DeleteInstance", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "DeleteInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.DeleteInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_instance" + }, + "description": "Sample for DeleteInstance", + "file": "lustre_v1_generated_lustre_delete_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_DeleteInstance_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": "lustre_v1_generated_lustre_delete_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.lustre_v1.LustreClient", + "shortName": "LustreClient" + }, + "fullName": "google.cloud.lustre_v1.LustreClient.delete_instance", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.DeleteInstance", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "DeleteInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.DeleteInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_instance" + }, + "description": "Sample for DeleteInstance", + "file": "lustre_v1_generated_lustre_delete_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_DeleteInstance_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": "lustre_v1_generated_lustre_delete_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.lustre_v1.LustreAsyncClient", + "shortName": "LustreAsyncClient" + }, + "fullName": "google.cloud.lustre_v1.LustreAsyncClient.delete_mirror", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.DeleteMirror", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "DeleteMirror" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.DeleteMirrorRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_mirror" + }, + "description": "Sample for DeleteMirror", + "file": "lustre_v1_generated_lustre_delete_mirror_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_DeleteMirror_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": "lustre_v1_generated_lustre_delete_mirror_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.lustre_v1.LustreClient", + "shortName": "LustreClient" + }, + "fullName": "google.cloud.lustre_v1.LustreClient.delete_mirror", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.DeleteMirror", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "DeleteMirror" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.DeleteMirrorRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_mirror" + }, + "description": "Sample for DeleteMirror", + "file": "lustre_v1_generated_lustre_delete_mirror_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_DeleteMirror_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": "lustre_v1_generated_lustre_delete_mirror_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.lustre_v1.LustreAsyncClient", + "shortName": "LustreAsyncClient" + }, + "fullName": "google.cloud.lustre_v1.LustreAsyncClient.export_data", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.ExportData", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "ExportData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.ExportDataRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "export_data" + }, + "description": "Sample for ExportData", + "file": "lustre_v1_generated_lustre_export_data_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_ExportData_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "lustre_v1_generated_lustre_export_data_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.lustre_v1.LustreClient", + "shortName": "LustreClient" + }, + "fullName": "google.cloud.lustre_v1.LustreClient.export_data", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.ExportData", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "ExportData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.ExportDataRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "export_data" + }, + "description": "Sample for ExportData", + "file": "lustre_v1_generated_lustre_export_data_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_ExportData_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "lustre_v1_generated_lustre_export_data_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.lustre_v1.LustreAsyncClient", + "shortName": "LustreAsyncClient" + }, + "fullName": "google.cloud.lustre_v1.LustreAsyncClient.get_directory_policy", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.GetDirectoryPolicy", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "GetDirectoryPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.GetDirectoryPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.lustre_v1.types.DirectoryPolicy", + "shortName": "get_directory_policy" + }, + "description": "Sample for GetDirectoryPolicy", + "file": "lustre_v1_generated_lustre_get_directory_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_GetDirectoryPolicy_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": "lustre_v1_generated_lustre_get_directory_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.lustre_v1.LustreClient", + "shortName": "LustreClient" + }, + "fullName": "google.cloud.lustre_v1.LustreClient.get_directory_policy", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.GetDirectoryPolicy", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "GetDirectoryPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.GetDirectoryPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.lustre_v1.types.DirectoryPolicy", + "shortName": "get_directory_policy" + }, + "description": "Sample for GetDirectoryPolicy", + "file": "lustre_v1_generated_lustre_get_directory_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_GetDirectoryPolicy_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": "lustre_v1_generated_lustre_get_directory_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.lustre_v1.LustreAsyncClient", + "shortName": "LustreAsyncClient" + }, + "fullName": "google.cloud.lustre_v1.LustreAsyncClient.get_instance", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.GetInstance", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.GetInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.lustre_v1.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "lustre_v1_generated_lustre_get_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_GetInstance_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": "lustre_v1_generated_lustre_get_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.lustre_v1.LustreClient", + "shortName": "LustreClient" + }, + "fullName": "google.cloud.lustre_v1.LustreClient.get_instance", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.GetInstance", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.GetInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.lustre_v1.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "lustre_v1_generated_lustre_get_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_GetInstance_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": "lustre_v1_generated_lustre_get_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.lustre_v1.LustreAsyncClient", + "shortName": "LustreAsyncClient" + }, + "fullName": "google.cloud.lustre_v1.LustreAsyncClient.get_mirror", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.GetMirror", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "GetMirror" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.GetMirrorRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.lustre_v1.types.Mirror", + "shortName": "get_mirror" + }, + "description": "Sample for GetMirror", + "file": "lustre_v1_generated_lustre_get_mirror_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_GetMirror_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": "lustre_v1_generated_lustre_get_mirror_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.lustre_v1.LustreClient", + "shortName": "LustreClient" + }, + "fullName": "google.cloud.lustre_v1.LustreClient.get_mirror", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.GetMirror", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "GetMirror" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.GetMirrorRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.lustre_v1.types.Mirror", + "shortName": "get_mirror" + }, + "description": "Sample for GetMirror", + "file": "lustre_v1_generated_lustre_get_mirror_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_GetMirror_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": "lustre_v1_generated_lustre_get_mirror_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.lustre_v1.LustreAsyncClient", + "shortName": "LustreAsyncClient" + }, + "fullName": "google.cloud.lustre_v1.LustreAsyncClient.import_data", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.ImportData", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "ImportData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.ImportDataRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_data" + }, + "description": "Sample for ImportData", + "file": "lustre_v1_generated_lustre_import_data_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_ImportData_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "lustre_v1_generated_lustre_import_data_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.lustre_v1.LustreClient", + "shortName": "LustreClient" + }, + "fullName": "google.cloud.lustre_v1.LustreClient.import_data", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.ImportData", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "ImportData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.ImportDataRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_data" + }, + "description": "Sample for ImportData", + "file": "lustre_v1_generated_lustre_import_data_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_ImportData_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "lustre_v1_generated_lustre_import_data_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.lustre_v1.LustreAsyncClient", + "shortName": "LustreAsyncClient" + }, + "fullName": "google.cloud.lustre_v1.LustreAsyncClient.list_directory_policies", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.ListDirectoryPolicies", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "ListDirectoryPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.ListDirectoryPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.lustre_v1.services.lustre.pagers.ListDirectoryPoliciesAsyncPager", + "shortName": "list_directory_policies" + }, + "description": "Sample for ListDirectoryPolicies", + "file": "lustre_v1_generated_lustre_list_directory_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_ListDirectoryPolicies_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": "lustre_v1_generated_lustre_list_directory_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.lustre_v1.LustreClient", + "shortName": "LustreClient" + }, + "fullName": "google.cloud.lustre_v1.LustreClient.list_directory_policies", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.ListDirectoryPolicies", + "service": { + "fullName": "google.cloud.lustre.v1.Lustre", + "shortName": "Lustre" + }, + "shortName": "ListDirectoryPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.lustre_v1.types.ListDirectoryPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.lustre_v1.services.lustre.pagers.ListDirectoryPoliciesPager", + "shortName": "list_directory_policies" + }, + "description": "Sample for ListDirectoryPolicies", + "file": "lustre_v1_generated_lustre_list_directory_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "lustre_v1_generated_Lustre_ListDirectoryPolicies_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": "lustre_v1_generated_lustre_list_directory_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.lustre_v1.LustreAsyncClient", + "shortName": "LustreAsyncClient" + }, + "fullName": "google.cloud.lustre_v1.LustreAsyncClient.list_instances", + "method": { + "fullName": "google.cloud.lustre.v1.Lustre.ListInstances", "service": { "fullName": "google.cloud.lustre.v1.Lustre", "shortName": "Lustre" }, - "shortName": "ExportData" + "shortName": "ListInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.lustre_v1.types.ExportDataRequest" + "type": "google.cloud.lustre_v1.types.ListInstancesRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -384,22 +2022,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "export_data" + "resultType": "google.cloud.lustre_v1.services.lustre.pagers.ListInstancesAsyncPager", + "shortName": "list_instances" }, - "description": "Sample for ExportData", - "file": "lustre_v1_generated_lustre_export_data_async.py", + "description": "Sample for ListInstances", + "file": "lustre_v1_generated_lustre_list_instances_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "lustre_v1_generated_Lustre_ExportData_async", + "regionTag": "lustre_v1_generated_Lustre_ListInstances_async", "segments": [ { - "end": 59, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 52, "start": 27, "type": "SHORT" }, @@ -409,22 +2047,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 56, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 60, - "start": 57, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "lustre_v1_generated_lustre_export_data_async.py" + "title": "lustre_v1_generated_lustre_list_instances_async.py" }, { "canonical": true, @@ -433,19 +2071,23 @@ "fullName": "google.cloud.lustre_v1.LustreClient", "shortName": "LustreClient" }, - "fullName": "google.cloud.lustre_v1.LustreClient.export_data", + "fullName": "google.cloud.lustre_v1.LustreClient.list_instances", "method": { - "fullName": "google.cloud.lustre.v1.Lustre.ExportData", + "fullName": "google.cloud.lustre.v1.Lustre.ListInstances", "service": { "fullName": "google.cloud.lustre.v1.Lustre", "shortName": "Lustre" }, - "shortName": "ExportData" + "shortName": "ListInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.lustre_v1.types.ExportDataRequest" + "type": "google.cloud.lustre_v1.types.ListInstancesRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -460,22 +2102,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "export_data" + "resultType": "google.cloud.lustre_v1.services.lustre.pagers.ListInstancesPager", + "shortName": "list_instances" }, - "description": "Sample for ExportData", - "file": "lustre_v1_generated_lustre_export_data_sync.py", + "description": "Sample for ListInstances", + "file": "lustre_v1_generated_lustre_list_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "lustre_v1_generated_Lustre_ExportData_sync", + "regionTag": "lustre_v1_generated_Lustre_ListInstances_sync", "segments": [ { - "end": 59, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 52, "start": 27, "type": "SHORT" }, @@ -485,22 +2127,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 56, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 60, - "start": 57, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "lustre_v1_generated_lustre_export_data_sync.py" + "title": "lustre_v1_generated_lustre_list_instances_sync.py" }, { "canonical": true, @@ -510,22 +2152,22 @@ "fullName": "google.cloud.lustre_v1.LustreAsyncClient", "shortName": "LustreAsyncClient" }, - "fullName": "google.cloud.lustre_v1.LustreAsyncClient.get_instance", + "fullName": "google.cloud.lustre_v1.LustreAsyncClient.list_mirrors", "method": { - "fullName": "google.cloud.lustre.v1.Lustre.GetInstance", + "fullName": "google.cloud.lustre.v1.Lustre.ListMirrors", "service": { "fullName": "google.cloud.lustre.v1.Lustre", "shortName": "Lustre" }, - "shortName": "GetInstance" + "shortName": "ListMirrors" }, "parameters": [ { "name": "request", - "type": "google.cloud.lustre_v1.types.GetInstanceRequest" + "type": "google.cloud.lustre_v1.types.ListMirrorsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -541,22 +2183,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.lustre_v1.types.Instance", - "shortName": "get_instance" + "resultType": "google.cloud.lustre_v1.services.lustre.pagers.ListMirrorsAsyncPager", + "shortName": "list_mirrors" }, - "description": "Sample for GetInstance", - "file": "lustre_v1_generated_lustre_get_instance_async.py", + "description": "Sample for ListMirrors", + "file": "lustre_v1_generated_lustre_list_mirrors_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "lustre_v1_generated_Lustre_GetInstance_async", + "regionTag": "lustre_v1_generated_Lustre_ListMirrors_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -576,12 +2218,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "lustre_v1_generated_lustre_get_instance_async.py" + "title": "lustre_v1_generated_lustre_list_mirrors_async.py" }, { "canonical": true, @@ -590,22 +2232,22 @@ "fullName": "google.cloud.lustre_v1.LustreClient", "shortName": "LustreClient" }, - "fullName": "google.cloud.lustre_v1.LustreClient.get_instance", + "fullName": "google.cloud.lustre_v1.LustreClient.list_mirrors", "method": { - "fullName": "google.cloud.lustre.v1.Lustre.GetInstance", + "fullName": "google.cloud.lustre.v1.Lustre.ListMirrors", "service": { "fullName": "google.cloud.lustre.v1.Lustre", "shortName": "Lustre" }, - "shortName": "GetInstance" + "shortName": "ListMirrors" }, "parameters": [ { "name": "request", - "type": "google.cloud.lustre_v1.types.GetInstanceRequest" + "type": "google.cloud.lustre_v1.types.ListMirrorsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -621,22 +2263,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.lustre_v1.types.Instance", - "shortName": "get_instance" + "resultType": "google.cloud.lustre_v1.services.lustre.pagers.ListMirrorsPager", + "shortName": "list_mirrors" }, - "description": "Sample for GetInstance", - "file": "lustre_v1_generated_lustre_get_instance_sync.py", + "description": "Sample for ListMirrors", + "file": "lustre_v1_generated_lustre_list_mirrors_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "lustre_v1_generated_Lustre_GetInstance_sync", + "regionTag": "lustre_v1_generated_Lustre_ListMirrors_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -656,12 +2298,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "lustre_v1_generated_lustre_get_instance_sync.py" + "title": "lustre_v1_generated_lustre_list_mirrors_sync.py" }, { "canonical": true, @@ -671,24 +2313,28 @@ "fullName": "google.cloud.lustre_v1.LustreAsyncClient", "shortName": "LustreAsyncClient" }, - "fullName": "google.cloud.lustre_v1.LustreAsyncClient.import_data", + "fullName": "google.cloud.lustre_v1.LustreAsyncClient.reschedule_maintenance", "method": { - "fullName": "google.cloud.lustre.v1.Lustre.ImportData", + "fullName": "google.cloud.lustre.v1.Lustre.RescheduleMaintenance", "service": { "fullName": "google.cloud.lustre.v1.Lustre", "shortName": "Lustre" }, - "shortName": "ImportData" + "shortName": "RescheduleMaintenance" }, "parameters": [ { "name": "request", - "type": "google.cloud.lustre_v1.types.ImportDataRequest" + "type": "google.cloud.lustre_v1.types.RescheduleMaintenanceRequest" }, { "name": "name", "type": "str" }, + { + "name": "reschedule", + "type": "google.cloud.lustre_v1.types.RescheduleMaintenanceRequest.Reschedule" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -703,13 +2349,13 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_data" + "shortName": "reschedule_maintenance" }, - "description": "Sample for ImportData", - "file": "lustre_v1_generated_lustre_import_data_async.py", + "description": "Sample for RescheduleMaintenance", + "file": "lustre_v1_generated_lustre_reschedule_maintenance_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "lustre_v1_generated_Lustre_ImportData_async", + "regionTag": "lustre_v1_generated_Lustre_RescheduleMaintenance_async", "segments": [ { "end": 59, @@ -742,7 +2388,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "lustre_v1_generated_lustre_import_data_async.py" + "title": "lustre_v1_generated_lustre_reschedule_maintenance_async.py" }, { "canonical": true, @@ -751,24 +2397,28 @@ "fullName": "google.cloud.lustre_v1.LustreClient", "shortName": "LustreClient" }, - "fullName": "google.cloud.lustre_v1.LustreClient.import_data", + "fullName": "google.cloud.lustre_v1.LustreClient.reschedule_maintenance", "method": { - "fullName": "google.cloud.lustre.v1.Lustre.ImportData", + "fullName": "google.cloud.lustre.v1.Lustre.RescheduleMaintenance", "service": { "fullName": "google.cloud.lustre.v1.Lustre", "shortName": "Lustre" }, - "shortName": "ImportData" + "shortName": "RescheduleMaintenance" }, "parameters": [ { "name": "request", - "type": "google.cloud.lustre_v1.types.ImportDataRequest" + "type": "google.cloud.lustre_v1.types.RescheduleMaintenanceRequest" }, { "name": "name", "type": "str" }, + { + "name": "reschedule", + "type": "google.cloud.lustre_v1.types.RescheduleMaintenanceRequest.Reschedule" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -783,13 +2433,13 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "import_data" + "shortName": "reschedule_maintenance" }, - "description": "Sample for ImportData", - "file": "lustre_v1_generated_lustre_import_data_sync.py", + "description": "Sample for RescheduleMaintenance", + "file": "lustre_v1_generated_lustre_reschedule_maintenance_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "lustre_v1_generated_Lustre_ImportData_sync", + "regionTag": "lustre_v1_generated_Lustre_RescheduleMaintenance_sync", "segments": [ { "end": 59, @@ -822,7 +2472,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "lustre_v1_generated_lustre_import_data_sync.py" + "title": "lustre_v1_generated_lustre_reschedule_maintenance_sync.py" }, { "canonical": true, @@ -832,23 +2482,27 @@ "fullName": "google.cloud.lustre_v1.LustreAsyncClient", "shortName": "LustreAsyncClient" }, - "fullName": "google.cloud.lustre_v1.LustreAsyncClient.list_instances", + "fullName": "google.cloud.lustre_v1.LustreAsyncClient.update_instance", "method": { - "fullName": "google.cloud.lustre.v1.Lustre.ListInstances", + "fullName": "google.cloud.lustre.v1.Lustre.UpdateInstance", "service": { "fullName": "google.cloud.lustre.v1.Lustre", "shortName": "Lustre" }, - "shortName": "ListInstances" + "shortName": "UpdateInstance" }, "parameters": [ { "name": "request", - "type": "google.cloud.lustre_v1.types.ListInstancesRequest" + "type": "google.cloud.lustre_v1.types.UpdateInstanceRequest" }, { - "name": "parent", - "type": "str" + "name": "instance", + "type": "google.cloud.lustre_v1.types.Instance" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -863,22 +2517,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.lustre_v1.services.lustre.pagers.ListInstancesAsyncPager", - "shortName": "list_instances" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_instance" }, - "description": "Sample for ListInstances", - "file": "lustre_v1_generated_lustre_list_instances_async.py", + "description": "Sample for UpdateInstance", + "file": "lustre_v1_generated_lustre_update_instance_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "lustre_v1_generated_Lustre_ListInstances_async", + "regionTag": "lustre_v1_generated_Lustre_UpdateInstance_async", "segments": [ { - "end": 52, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 60, "start": 27, "type": "SHORT" }, @@ -888,22 +2542,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "lustre_v1_generated_lustre_list_instances_async.py" + "title": "lustre_v1_generated_lustre_update_instance_async.py" }, { "canonical": true, @@ -912,23 +2566,27 @@ "fullName": "google.cloud.lustre_v1.LustreClient", "shortName": "LustreClient" }, - "fullName": "google.cloud.lustre_v1.LustreClient.list_instances", + "fullName": "google.cloud.lustre_v1.LustreClient.update_instance", "method": { - "fullName": "google.cloud.lustre.v1.Lustre.ListInstances", + "fullName": "google.cloud.lustre.v1.Lustre.UpdateInstance", "service": { "fullName": "google.cloud.lustre.v1.Lustre", "shortName": "Lustre" }, - "shortName": "ListInstances" + "shortName": "UpdateInstance" }, "parameters": [ { "name": "request", - "type": "google.cloud.lustre_v1.types.ListInstancesRequest" + "type": "google.cloud.lustre_v1.types.UpdateInstanceRequest" }, { - "name": "parent", - "type": "str" + "name": "instance", + "type": "google.cloud.lustre_v1.types.Instance" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -943,22 +2601,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.lustre_v1.services.lustre.pagers.ListInstancesPager", - "shortName": "list_instances" + "resultType": "google.api_core.operation.Operation", + "shortName": "update_instance" }, - "description": "Sample for ListInstances", - "file": "lustre_v1_generated_lustre_list_instances_sync.py", + "description": "Sample for UpdateInstance", + "file": "lustre_v1_generated_lustre_update_instance_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "lustre_v1_generated_Lustre_ListInstances_sync", + "regionTag": "lustre_v1_generated_Lustre_UpdateInstance_sync", "segments": [ { - "end": 52, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 60, "start": 27, "type": "SHORT" }, @@ -968,22 +2626,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "lustre_v1_generated_lustre_list_instances_sync.py" + "title": "lustre_v1_generated_lustre_update_instance_sync.py" }, { "canonical": true, @@ -993,23 +2651,23 @@ "fullName": "google.cloud.lustre_v1.LustreAsyncClient", "shortName": "LustreAsyncClient" }, - "fullName": "google.cloud.lustre_v1.LustreAsyncClient.update_instance", + "fullName": "google.cloud.lustre_v1.LustreAsyncClient.update_mirror", "method": { - "fullName": "google.cloud.lustre.v1.Lustre.UpdateInstance", + "fullName": "google.cloud.lustre.v1.Lustre.UpdateMirror", "service": { "fullName": "google.cloud.lustre.v1.Lustre", "shortName": "Lustre" }, - "shortName": "UpdateInstance" + "shortName": "UpdateMirror" }, "parameters": [ { "name": "request", - "type": "google.cloud.lustre_v1.types.UpdateInstanceRequest" + "type": "google.cloud.lustre_v1.types.UpdateMirrorRequest" }, { - "name": "instance", - "type": "google.cloud.lustre_v1.types.Instance" + "name": "mirror", + "type": "google.cloud.lustre_v1.types.Mirror" }, { "name": "update_mask", @@ -1029,21 +2687,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_instance" + "shortName": "update_mirror" }, - "description": "Sample for UpdateInstance", - "file": "lustre_v1_generated_lustre_update_instance_async.py", + "description": "Sample for UpdateMirror", + "file": "lustre_v1_generated_lustre_update_mirror_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "lustre_v1_generated_Lustre_UpdateInstance_async", + "regionTag": "lustre_v1_generated_Lustre_UpdateMirror_async", "segments": [ { - "end": 61, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 59, "start": 27, "type": "SHORT" }, @@ -1053,22 +2711,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "lustre_v1_generated_lustre_update_instance_async.py" + "title": "lustre_v1_generated_lustre_update_mirror_async.py" }, { "canonical": true, @@ -1077,23 +2735,23 @@ "fullName": "google.cloud.lustre_v1.LustreClient", "shortName": "LustreClient" }, - "fullName": "google.cloud.lustre_v1.LustreClient.update_instance", + "fullName": "google.cloud.lustre_v1.LustreClient.update_mirror", "method": { - "fullName": "google.cloud.lustre.v1.Lustre.UpdateInstance", + "fullName": "google.cloud.lustre.v1.Lustre.UpdateMirror", "service": { "fullName": "google.cloud.lustre.v1.Lustre", "shortName": "Lustre" }, - "shortName": "UpdateInstance" + "shortName": "UpdateMirror" }, "parameters": [ { "name": "request", - "type": "google.cloud.lustre_v1.types.UpdateInstanceRequest" + "type": "google.cloud.lustre_v1.types.UpdateMirrorRequest" }, { - "name": "instance", - "type": "google.cloud.lustre_v1.types.Instance" + "name": "mirror", + "type": "google.cloud.lustre_v1.types.Mirror" }, { "name": "update_mask", @@ -1113,21 +2771,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "update_instance" + "shortName": "update_mirror" }, - "description": "Sample for UpdateInstance", - "file": "lustre_v1_generated_lustre_update_instance_sync.py", + "description": "Sample for UpdateMirror", + "file": "lustre_v1_generated_lustre_update_mirror_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "lustre_v1_generated_Lustre_UpdateInstance_sync", + "regionTag": "lustre_v1_generated_Lustre_UpdateMirror_sync", "segments": [ { - "end": 61, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 59, "start": 27, "type": "SHORT" }, @@ -1137,22 +2795,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "lustre_v1_generated_lustre_update_instance_sync.py" + "title": "lustre_v1_generated_lustre_update_mirror_sync.py" } ] } diff --git a/packages/google-cloud-lustre/setup.py b/packages/google-cloud-lustre/setup.py index d343c0d57d9d..c688212b31aa 100644 --- a/packages/google-cloud-lustre/setup.py +++ b/packages/google-cloud-lustre/setup.py @@ -50,6 +50,7 @@ "grpcio >= 1.75.1, < 2.0.0; python_version >= '3.14'", "proto-plus >= 1.26.1, <2.0.0", "protobuf >= 6.33.5, < 8.0.0", + "grpc-google-iam-v1 >= 0.14.2, <1.0.0", ] extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-lustre" diff --git a/packages/google-cloud-lustre/testing/constraints-3.10.txt b/packages/google-cloud-lustre/testing/constraints-3.10.txt index 0dadf6857ff5..9c33fedfb264 100644 --- a/packages/google-cloud-lustre/testing/constraints-3.10.txt +++ b/packages/google-cloud-lustre/testing/constraints-3.10.txt @@ -9,3 +9,4 @@ google-auth==2.14.1 grpcio==1.59.0 proto-plus==1.26.1 protobuf==6.33.5 +grpc-google-iam-v1==0.14.2 diff --git a/packages/google-cloud-lustre/testing/constraints-3.11.txt b/packages/google-cloud-lustre/testing/constraints-3.11.txt index 7599dea499ed..1cd0c5a2c3d4 100644 --- a/packages/google-cloud-lustre/testing/constraints-3.11.txt +++ b/packages/google-cloud-lustre/testing/constraints-3.11.txt @@ -8,3 +8,4 @@ proto-plus protobuf # cryptography is a direct dependency of google-auth cryptography +grpc-google-iam-v1 diff --git a/packages/google-cloud-lustre/testing/constraints-3.12.txt b/packages/google-cloud-lustre/testing/constraints-3.12.txt index 7599dea499ed..1cd0c5a2c3d4 100644 --- a/packages/google-cloud-lustre/testing/constraints-3.12.txt +++ b/packages/google-cloud-lustre/testing/constraints-3.12.txt @@ -8,3 +8,4 @@ proto-plus protobuf # cryptography is a direct dependency of google-auth cryptography +grpc-google-iam-v1 diff --git a/packages/google-cloud-lustre/testing/constraints-3.13.txt b/packages/google-cloud-lustre/testing/constraints-3.13.txt index 6bd7e1f5b03d..f85022a2fb62 100644 --- a/packages/google-cloud-lustre/testing/constraints-3.13.txt +++ b/packages/google-cloud-lustre/testing/constraints-3.13.txt @@ -10,3 +10,4 @@ google-auth>=2 grpcio>=1 proto-plus>=1 protobuf>=7 +grpc-google-iam-v1>=0 diff --git a/packages/google-cloud-lustre/testing/constraints-3.14.txt b/packages/google-cloud-lustre/testing/constraints-3.14.txt index 6bd7e1f5b03d..f85022a2fb62 100644 --- a/packages/google-cloud-lustre/testing/constraints-3.14.txt +++ b/packages/google-cloud-lustre/testing/constraints-3.14.txt @@ -10,3 +10,4 @@ google-auth>=2 grpcio>=1 proto-plus>=1 protobuf>=7 +grpc-google-iam-v1>=0 diff --git a/packages/google-cloud-lustre/testing/constraints-3.15.txt b/packages/google-cloud-lustre/testing/constraints-3.15.txt index 6bd7e1f5b03d..f85022a2fb62 100644 --- a/packages/google-cloud-lustre/testing/constraints-3.15.txt +++ b/packages/google-cloud-lustre/testing/constraints-3.15.txt @@ -10,3 +10,4 @@ google-auth>=2 grpcio>=1 proto-plus>=1 protobuf>=7 +grpc-google-iam-v1>=0 diff --git a/packages/google-cloud-lustre/tests/unit/gapic/lustre_v1/test_lustre.py b/packages/google-cloud-lustre/tests/unit/gapic/lustre_v1/test_lustre.py index 01b3b2438083..50a0702af2d8 100644 --- a/packages/google-cloud-lustre/tests/unit/gapic/lustre_v1/test_lustre.py +++ b/packages/google-cloud-lustre/tests/unit/gapic/lustre_v1/test_lustre.py @@ -43,6 +43,9 @@ import google.protobuf.empty_pb2 as empty_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.type.date_pb2 as date_pb2 # type: ignore +import google.type.dayofweek_pb2 as dayofweek_pb2 # type: ignore +import google.type.timeofday_pb2 as timeofday_pb2 # type: ignore from google.api_core import ( client_options, future, @@ -58,6 +61,11 @@ from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.location import locations_pb2 +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + options_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account @@ -67,8 +75,10 @@ pagers, transports, ) -from google.cloud.lustre_v1.types import instance, transfer +from google.cloud.lustre_v1.types import directory_policy, instance, mirror, transfer +from google.cloud.lustre_v1.types import directory_policy as gcl_directory_policy from google.cloud.lustre_v1.types import instance as gcl_instance +from google.cloud.lustre_v1.types import mirror as gcl_mirror CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -1590,6 +1600,13 @@ def test_get_instance(request_type, transport: str = "grpc"): description="description_value", per_unit_storage_throughput=2931, gke_support_enabled=True, + kms_key="kms_key_value", + state_reason="state_reason_value", + placement_policy="placement_policy_value", + uid="uid_value", + available_version="available_version_value", + target_version="target_version_value", + effective_version="effective_version_value", ) response = client.get_instance(request) @@ -1610,6 +1627,13 @@ def test_get_instance(request_type, transport: str = "grpc"): assert response.description == "description_value" assert response.per_unit_storage_throughput == 2931 assert response.gke_support_enabled is True + assert response.kms_key == "kms_key_value" + assert response.state_reason == "state_reason_value" + assert response.placement_policy == "placement_policy_value" + assert response.uid == "uid_value" + assert response.available_version == "available_version_value" + assert response.target_version == "target_version_value" + assert response.effective_version == "effective_version_value" def test_get_instance_non_empty_request_with_auto_populated_field(): @@ -1750,6 +1774,13 @@ async def test_get_instance_async(request_type, transport: str = "grpc_asyncio") description="description_value", per_unit_storage_throughput=2931, gke_support_enabled=True, + kms_key="kms_key_value", + state_reason="state_reason_value", + placement_policy="placement_policy_value", + uid="uid_value", + available_version="available_version_value", + target_version="target_version_value", + effective_version="effective_version_value", ) ) response = await client.get_instance(request) @@ -1771,6 +1802,13 @@ async def test_get_instance_async(request_type, transport: str = "grpc_asyncio") assert response.description == "description_value" assert response.per_unit_storage_throughput == 2931 assert response.gke_support_enabled is True + assert response.kms_key == "kms_key_value" + assert response.state_reason == "state_reason_value" + assert response.placement_policy == "placement_policy_value" + assert response.uid == "uid_value" + assert response.available_version == "available_version_value" + assert response.target_version == "target_version_value" + assert response.effective_version == "effective_version_value" def test_get_instance_field_headers(): @@ -2927,11 +2965,11 @@ async def test_delete_instance_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - transfer.ImportDataRequest(), + instance.RescheduleMaintenanceRequest(), {}, ], ) -def test_import_data(request_type, transport: str = "grpc"): +def test_reschedule_maintenance(request_type, transport: str = "grpc"): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2942,22 +2980,24 @@ def test_import_data(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_data), "__call__") as call: + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.import_data(request) + response = client.reschedule_maintenance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = transfer.ImportDataRequest() + request = instance.RescheduleMaintenanceRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_import_data_non_empty_request_with_auto_populated_field(): +def test_reschedule_maintenance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = LustreClient( @@ -2968,27 +3008,27 @@ def test_import_data_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = transfer.ImportDataRequest( + request = instance.RescheduleMaintenanceRequest( name="name_value", - service_account="service_account_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_data), "__call__") as call: + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.import_data(request=request) + client.reschedule_maintenance(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = transfer.ImportDataRequest( + request_msg = instance.RescheduleMaintenanceRequest( name="name_value", - service_account="service_account_value", ) assert args[0] == request_msg -def test_import_data_use_cached_wrapped_rpc(): +def test_reschedule_maintenance_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -3002,16 +3042,21 @@ def test_import_data_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.import_data in client._transport._wrapped_methods + assert ( + client._transport.reschedule_maintenance + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.import_data] = mock_rpc + client._transport._wrapped_methods[client._transport.reschedule_maintenance] = ( + mock_rpc + ) request = {} - client.import_data(request) + client.reschedule_maintenance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3021,7 +3066,7 @@ def test_import_data_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.import_data(request) + client.reschedule_maintenance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3029,7 +3074,7 @@ def test_import_data_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_import_data_async_use_cached_wrapped_rpc( +async def test_reschedule_maintenance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -3046,7 +3091,7 @@ async def test_import_data_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.import_data + client._client._transport.reschedule_maintenance in client._client._transport._wrapped_methods ) @@ -3054,11 +3099,11 @@ async def test_import_data_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.import_data + client._client._transport.reschedule_maintenance ] = mock_rpc request = {} - await client.import_data(request) + await client.reschedule_maintenance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3068,7 +3113,7 @@ async def test_import_data_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.import_data(request) + await client.reschedule_maintenance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3079,11 +3124,13 @@ async def test_import_data_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - transfer.ImportDataRequest(), + instance.RescheduleMaintenanceRequest(), {}, ], ) -async def test_import_data_async(request_type, transport: str = "grpc_asyncio"): +async def test_reschedule_maintenance_async( + request_type, transport: str = "grpc_asyncio" +): client = LustreAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3094,38 +3141,42 @@ async def test_import_data_async(request_type, transport: str = "grpc_asyncio"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_data), "__call__") as call: + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__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.import_data(request) + response = await client.reschedule_maintenance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = transfer.ImportDataRequest() + request = instance.RescheduleMaintenanceRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_import_data_field_headers(): +def test_reschedule_maintenance_field_headers(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = transfer.ImportDataRequest() + request = instance.RescheduleMaintenanceRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_data), "__call__") as call: + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.import_data(request) + client.reschedule_maintenance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3141,23 +3192,25 @@ def test_import_data_field_headers(): @pytest.mark.asyncio -async def test_import_data_field_headers_async(): +async def test_reschedule_maintenance_field_headers_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = transfer.ImportDataRequest() + request = instance.RescheduleMaintenanceRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_data), "__call__") as call: + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.import_data(request) + await client.reschedule_maintenance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -3172,19 +3225,24 @@ async def test_import_data_field_headers_async(): ) in kw["metadata"] -def test_import_data_flattened(): +def test_reschedule_maintenance_flattened(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_data), "__call__") as call: + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__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.import_data( + client.reschedule_maintenance( name="name_value", + reschedule=instance.RescheduleMaintenanceRequest.Reschedule( + reschedule_type=instance.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE + ), ) # Establish that the underlying call was made with the expected @@ -3194,9 +3252,14 @@ def test_import_data_flattened(): arg = args[0].name mock_val = "name_value" assert arg == mock_val + arg = args[0].reschedule + mock_val = instance.RescheduleMaintenanceRequest.Reschedule( + reschedule_type=instance.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE + ) + assert arg == mock_val -def test_import_data_flattened_error(): +def test_reschedule_maintenance_flattened_error(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -3204,20 +3267,25 @@ def test_import_data_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.import_data( - transfer.ImportDataRequest(), + client.reschedule_maintenance( + instance.RescheduleMaintenanceRequest(), name="name_value", + reschedule=instance.RescheduleMaintenanceRequest.Reschedule( + reschedule_type=instance.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE + ), ) @pytest.mark.asyncio -async def test_import_data_flattened_async(): +async def test_reschedule_maintenance_flattened_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_data), "__call__") as call: + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -3226,8 +3294,11 @@ async def test_import_data_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.import_data( + response = await client.reschedule_maintenance( name="name_value", + reschedule=instance.RescheduleMaintenanceRequest.Reschedule( + reschedule_type=instance.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE + ), ) # Establish that the underlying call was made with the expected @@ -3237,10 +3308,15 @@ async def test_import_data_flattened_async(): arg = args[0].name mock_val = "name_value" assert arg == mock_val + arg = args[0].reschedule + mock_val = instance.RescheduleMaintenanceRequest.Reschedule( + reschedule_type=instance.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE + ) + assert arg == mock_val @pytest.mark.asyncio -async def test_import_data_flattened_error_async(): +async def test_reschedule_maintenance_flattened_error_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) @@ -3248,20 +3324,23 @@ async def test_import_data_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.import_data( - transfer.ImportDataRequest(), + await client.reschedule_maintenance( + instance.RescheduleMaintenanceRequest(), name="name_value", + reschedule=instance.RescheduleMaintenanceRequest.Reschedule( + reschedule_type=instance.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE + ), ) @pytest.mark.parametrize( "request_type", [ - transfer.ExportDataRequest(), + transfer.ImportDataRequest(), {}, ], ) -def test_export_data(request_type, transport: str = "grpc"): +def test_import_data(request_type, transport: str = "grpc"): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3272,22 +3351,22 @@ def test_export_data(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_data), "__call__") as call: + with mock.patch.object(type(client.transport.import_data), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.export_data(request) + response = client.import_data(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = transfer.ExportDataRequest() + request = transfer.ImportDataRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_export_data_non_empty_request_with_auto_populated_field(): +def test_import_data_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = LustreClient( @@ -3298,27 +3377,27 @@ def test_export_data_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = transfer.ExportDataRequest( + request = transfer.ImportDataRequest( name="name_value", service_account="service_account_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_data), "__call__") as call: + with mock.patch.object(type(client.transport.import_data), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.export_data(request=request) + client.import_data(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = transfer.ExportDataRequest( + request_msg = transfer.ImportDataRequest( name="name_value", service_account="service_account_value", ) assert args[0] == request_msg -def test_export_data_use_cached_wrapped_rpc(): +def test_import_data_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -3332,16 +3411,16 @@ def test_export_data_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.export_data in client._transport._wrapped_methods + assert client._transport.import_data in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.export_data] = mock_rpc + client._transport._wrapped_methods[client._transport.import_data] = mock_rpc request = {} - client.export_data(request) + client.import_data(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3351,7 +3430,7 @@ def test_export_data_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.export_data(request) + client.import_data(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3359,7 +3438,7 @@ def test_export_data_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_export_data_async_use_cached_wrapped_rpc( +async def test_import_data_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -3376,7 +3455,7 @@ async def test_export_data_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.export_data + client._client._transport.import_data in client._client._transport._wrapped_methods ) @@ -3384,11 +3463,11 @@ async def test_export_data_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.export_data + client._client._transport.import_data ] = mock_rpc request = {} - await client.export_data(request) + await client.import_data(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3398,7 +3477,7 @@ async def test_export_data_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.export_data(request) + await client.import_data(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3409,11 +3488,11 @@ async def test_export_data_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - transfer.ExportDataRequest(), + transfer.ImportDataRequest(), {}, ], ) -async def test_export_data_async(request_type, transport: str = "grpc_asyncio"): +async def test_import_data_async(request_type, transport: str = "grpc_asyncio"): client = LustreAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3424,38 +3503,38 @@ async def test_export_data_async(request_type, transport: str = "grpc_asyncio"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_data), "__call__") as call: + with mock.patch.object(type(client.transport.import_data), "__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.export_data(request) + response = await client.import_data(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = transfer.ExportDataRequest() + request = transfer.ImportDataRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_export_data_field_headers(): +def test_import_data_field_headers(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = transfer.ExportDataRequest() + request = transfer.ImportDataRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_data), "__call__") as call: + with mock.patch.object(type(client.transport.import_data), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.export_data(request) + client.import_data(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3471,23 +3550,23 @@ def test_export_data_field_headers(): @pytest.mark.asyncio -async def test_export_data_field_headers_async(): +async def test_import_data_field_headers_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = transfer.ExportDataRequest() + request = transfer.ImportDataRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_data), "__call__") as call: + with mock.patch.object(type(client.transport.import_data), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.export_data(request) + await client.import_data(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -3502,255 +3581,159 @@ async def test_export_data_field_headers_async(): ) in kw["metadata"] -def test_list_instances_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +def test_import_data_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.import_data), "__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.import_data( + name="name_value", ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Establish that the 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 - # Ensure method has been cached - assert client._transport.list_instances in client._transport._wrapped_methods - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. +def test_import_data_flattened_error(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.import_data( + transfer.ImportDataRequest(), + name="name_value", ) - client._transport._wrapped_methods[client._transport.list_instances] = mock_rpc - request = {} - client.list_instances(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 +@pytest.mark.asyncio +async def test_import_data_flattened_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) - client.list_instances(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.import_data), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + 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.import_data( + 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 -def test_list_instances_rest_required_fields( - request_type=instance.ListInstancesRequest, -): - transport_class = transports.LustreRestTransport - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +@pytest.mark.asyncio +async def test_import_data_flattened_error_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), ) - # verify fields with default values are dropped + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.import_data( + transfer.ImportDataRequest(), + name="name_value", + ) - default_values = getattr( - transport_class._BaseListInstances, - "_BaseListInstances__REQUIRED_FIELDS_DEFAULT_VALUES", + +@pytest.mark.parametrize( + "request_type", + [ + transfer.ExportDataRequest(), {}, + ], +) +def test_export_data(request_type, transport: str = "grpc"): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = "parent_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = instance.ListInstancesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = instance.ListInstancesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_data), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.export_data(request) - response = client.list_instances(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = transfer.ExportDataRequest() + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_list_instances_rest_flattened(): +def test_export_data_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = instance.ListInstancesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = instance.ListInstancesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_instances(**mock_args) - - # Establish that the underlying call 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/*}/instances" % client.transport._host, - args[1], - ) - - -def test_list_instances_rest_flattened_error(transport: str = "rest"): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = transfer.ExportDataRequest( + name="name_value", + service_account="service_account_value", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_instances( - instance.ListInstancesRequest(), - parent="parent_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_data), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - - -def test_list_instances_rest_pager(transport: str = "rest"): - client = LustreClient( - 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 = ( - instance.ListInstancesResponse( - instances=[ - instance.Instance(), - instance.Instance(), - instance.Instance(), - ], - next_page_token="abc", - ), - instance.ListInstancesResponse( - instances=[], - next_page_token="def", - ), - instance.ListInstancesResponse( - instances=[ - instance.Instance(), - ], - next_page_token="ghi", - ), - instance.ListInstancesResponse( - instances=[ - instance.Instance(), - instance.Instance(), - ], - ), + client.export_data(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = transfer.ExportDataRequest( + name="name_value", + service_account="service_account_value", ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(instance.ListInstancesResponse.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_instances(request=sample_request) - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, instance.Instance) for i in results) - - pages = list(client.list_instances(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + assert args[0] == request_msg -def test_get_instance_rest_use_cached_wrapped_rpc(): +def test_export_data_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -3758,167 +3741,247 @@ def test_get_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_instance in client._transport._wrapped_methods + assert client._transport.export_data in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_instance] = mock_rpc - + client._transport._wrapped_methods[client._transport.export_data] = mock_rpc request = {} - client.get_instance(request) + client.export_data(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_instance(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.export_data(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_instance_rest_required_fields(request_type=instance.GetInstanceRequest): - transport_class = transports.LustreRestTransport +@pytest.mark.asyncio +async def test_export_data_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.export_data + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseGetInstance, - "_BaseGetInstance__REQUIRED_FIELDS_DEFAULT_VALUES", + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.export_data + ] = mock_rpc + + request = {} + await client.export_data(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.export_data(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + transfer.ExportDataRequest(), {}, + ], +) +async def test_export_data_async(request_type, transport: str = "grpc_asyncio"): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - jsonified_request["name"] = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_data), "__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.export_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = transfer.ExportDataRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_export_data_field_headers(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = instance.Instance() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force 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 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.ExportDataRequest() - # Convert return value to protobuf type - return_value = instance.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + request.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_data), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_data(request) - response = client.get_instance(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # 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_instance_rest_flattened(): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_export_data_field_headers_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = instance.Instance() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transfer.ExportDataRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/instances/sample3" - } + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_data), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = instance.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + await client.export_data(request) - client.get_instance(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Establish that the underlying call 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/*/instances/*}" % client.transport._host, - args[1], - ) + # 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_instance_rest_flattened_error(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + gcl_mirror.CreateMirrorRequest(), + {}, + ], +) +def test_create_mirror(request_type, transport: str = "grpc"): client = LustreClient( credentials=ga_credentials.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_instance( - instance.GetInstanceRequest(), - name="name_value", + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mirror), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_mirror(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcl_mirror.CreateMirrorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_mirror_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcl_mirror.CreateMirrorRequest( + parent="parent_value", + mirror_id="mirror_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_mirror), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_mirror(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcl_mirror.CreateMirrorRequest( + parent="parent_value", + mirror_id="mirror_id_value", ) + assert args[0] == request_msg -def test_create_instance_rest_use_cached_wrapped_rpc(): +def test_create_mirror_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -3926,368 +3989,343 @@ def test_create_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_instance in client._transport._wrapped_methods + assert client._transport.create_mirror in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_instance] = mock_rpc - + client._transport._wrapped_methods[client._transport.create_mirror] = mock_rpc request = {} - client.create_instance(request) + client.create_mirror(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_instance(request) + client.create_mirror(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_instance_rest_required_fields( - request_type=gcl_instance.CreateInstanceRequest, +@pytest.mark.asyncio +async def test_create_mirror_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.LustreRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request_init["instance_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped - assert "instanceId" not in jsonified_request + # Ensure method has been cached + assert ( + client._client._transport.create_mirror + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseCreateInstance, - "_BaseCreateInstance__REQUIRED_FIELDS_DEFAULT_VALUES", + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_mirror + ] = mock_rpc + + request = {} + await client.create_mirror(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_mirror(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + gcl_mirror.CreateMirrorRequest(), {}, + ], +) +async def test_create_mirror_async(request_type, transport: str = "grpc_asyncio"): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == request_init["instance_id"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["instanceId"] = "instance_id_value" + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "instanceId", - "requestId", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_mirror), "__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_mirror(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcl_mirror.CreateMirrorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == "instance_id_value" +def test_create_mirror_field_headers(): client = LustreClient( 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 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcl_mirror.CreateMirrorRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_mirror), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_mirror(request) - response = client.create_instance(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [ - ( - "instanceId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # 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_instance_rest_flattened(): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_create_mirror_field_headers_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcl_mirror.CreateMirrorRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - instance=gcl_instance.Instance(name="name_value"), - instance_id="instance_id_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_mirror), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.create_mirror(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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.create_instance(**mock_args) + # 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_mirror_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_mirror), "__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_mirror( + parent="parent_value", + mirror=gcl_mirror.Mirror(name="name_value"), + mirror_id="mirror_id_value", + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/instances" % client.transport._host, - args[1], - ) + 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].mirror + mock_val = gcl_mirror.Mirror(name="name_value") + assert arg == mock_val + arg = args[0].mirror_id + mock_val = "mirror_id_value" + assert arg == mock_val -def test_create_instance_rest_flattened_error(transport: str = "rest"): +def test_create_mirror_flattened_error(): client = LustreClient( credentials=ga_credentials.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_instance( - gcl_instance.CreateInstanceRequest(), + client.create_mirror( + gcl_mirror.CreateMirrorRequest(), parent="parent_value", - instance=gcl_instance.Instance(name="name_value"), - instance_id="instance_id_value", + mirror=gcl_mirror.Mirror(name="name_value"), + mirror_id="mirror_id_value", ) -def test_update_instance_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.asyncio +async def test_create_mirror_flattened_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.update_instance in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_mirror), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + 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_mirror( + parent="parent_value", + mirror=gcl_mirror.Mirror(name="name_value"), + mirror_id="mirror_id_value", ) - client._transport._wrapped_methods[client._transport.update_instance] = mock_rpc - - request = {} - client.update_instance(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Establish that 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].mirror + mock_val = gcl_mirror.Mirror(name="name_value") + assert arg == mock_val + arg = args[0].mirror_id + mock_val = "mirror_id_value" + assert arg == mock_val - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - client.update_instance(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_instance_rest_required_fields( - request_type=gcl_instance.UpdateInstanceRequest, -): - transport_class = transports.LustreRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - default_values = getattr( - transport_class._BaseUpdateInstance, - "_BaseUpdateInstance__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_create_mirror_flattened_error_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "requestId", - "updateMask", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_mirror( + gcl_mirror.CreateMirrorRequest(), + parent="parent_value", + mirror=gcl_mirror.Mirror(name="name_value"), + mirror_id="mirror_id_value", ) - ) - # verify required fields with non-default values are left alone +@pytest.mark.parametrize( + "request_type", + [ + gcl_mirror.UpdateMirrorRequest(), + {}, + ], +) +def test_update_mirror(request_type, transport: str = "grpc"): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - 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) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_mirror), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_mirror(request) - response = client.update_instance(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcl_mirror.UpdateMirrorRequest() + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_update_instance_rest_flattened(): +def test_update_mirror_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - # Mock the http request call within the method and fake a response. - with mock.patch.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 = { - "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} - } - - # get truthy value for each flattened field - mock_args = dict( - instance=gcl_instance.Instance(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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.update_instance(**mock_args) - - # Establish that the underlying call 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/{instance.name=projects/*/locations/*/instances/*}" - % client.transport._host, - args[1], - ) - - -def test_update_instance_rest_flattened_error(transport: str = "rest"): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcl_mirror.UpdateMirrorRequest() - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_instance( - gcl_instance.UpdateInstanceRequest(), - instance=gcl_instance.Instance(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_mirror), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client.update_mirror(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcl_mirror.UpdateMirrorRequest() + assert args[0] == request_msg -def test_delete_instance_rest_use_cached_wrapped_rpc(): +def test_update_mirror_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -4295,171 +4333,337 @@ def test_delete_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_instance in client._transport._wrapped_methods + assert client._transport.update_mirror in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_instance] = mock_rpc - + client._transport._wrapped_methods[client._transport.update_mirror] = mock_rpc request = {} - client.delete_instance(request) + client.update_mirror(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_instance(request) + client.update_mirror(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_instance_rest_required_fields( - request_type=instance.DeleteInstanceRequest, +@pytest.mark.asyncio +async def test_update_mirror_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.LustreRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # verify fields with default values are dropped + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - default_values = getattr( - transport_class._BaseDeleteInstance, - "_BaseDeleteInstance__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) + # Ensure method has been cached + assert ( + client._client._transport.update_mirror + in client._client._transport._wrapped_methods + ) - # verify required fields with default values are now present + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_mirror + ] = mock_rpc - jsonified_request["name"] = "name_value" + request = {} + await client.update_mirror(request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("requestId",)) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + await client.update_mirror(request) - # 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 + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + gcl_mirror.UpdateMirrorRequest(), + {}, + ], +) +async def test_update_mirror_async(request_type, transport: str = "grpc_asyncio"): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response = client.delete_instance(request) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_mirror), "__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_mirror(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcl_mirror.UpdateMirrorRequest() + assert args[0] == request -def test_delete_instance_rest_flattened(): + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_mirror_field_headers(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcl_mirror.UpdateMirrorRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/instances/sample3" - } + request.mirror.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_mirror), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_mirror(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "mirror.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_mirror_field_headers_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcl_mirror.UpdateMirrorRequest() + + request.mirror.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_mirror), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.update_mirror(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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.delete_instance(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "mirror.name=name_value", + ) in kw["metadata"] + + +def test_update_mirror_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_mirror), "__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_mirror( + mirror=gcl_mirror.Mirror(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(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/instances/*}" % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].mirror + mock_val = gcl_mirror.Mirror(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_delete_instance_rest_flattened_error(transport: str = "rest"): +def test_update_mirror_flattened_error(): client = LustreClient( credentials=ga_credentials.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_instance( - instance.DeleteInstanceRequest(), + client.update_mirror( + gcl_mirror.UpdateMirrorRequest(), + mirror=gcl_mirror.Mirror(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_mirror_flattened_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_mirror), "__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_mirror( + mirror=gcl_mirror.Mirror(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].mirror + mock_val = gcl_mirror.Mirror(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_mirror_flattened_error_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_mirror( + gcl_mirror.UpdateMirrorRequest(), + mirror=gcl_mirror.Mirror(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + mirror.DeleteMirrorRequest(), + {}, + ], +) +def test_delete_mirror(request_type, transport: str = "grpc"): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mirror), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_mirror(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = mirror.DeleteMirrorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_mirror_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = mirror.DeleteMirrorRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_mirror), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_mirror(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = mirror.DeleteMirrorRequest( name="name_value", ) + assert args[0] == request_msg -def test_import_data_rest_use_cached_wrapped_rpc(): +def test_delete_mirror_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -4467,2966 +4671,11792 @@ def test_import_data_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.import_data in client._transport._wrapped_methods + assert client._transport.delete_mirror in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.import_data] = mock_rpc - + client._transport._wrapped_methods[client._transport.delete_mirror] = mock_rpc request = {} - client.import_data(request) + client.delete_mirror(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.import_data(request) + client.delete_mirror(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_import_data_rest_required_fields(request_type=transfer.ImportDataRequest): - transport_class = transports.LustreRestTransport +@pytest.mark.asyncio +async def test_delete_mirror_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.delete_mirror + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseImportData, - "_BaseImportData__REQUIRED_FIELDS_DEFAULT_VALUES", + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_mirror + ] = mock_rpc + + request = {} + await client.delete_mirror(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_mirror(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + mirror.DeleteMirrorRequest(), {}, + ], +) +async def test_delete_mirror_async(request_type, transport: str = "grpc_asyncio"): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - jsonified_request["name"] = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_mirror), "__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_mirror(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = mirror.DeleteMirrorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_delete_mirror_field_headers(): client = LustreClient( 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 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = mirror.DeleteMirrorRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_mirror), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_mirror(request) - response = client.import_data(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # 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_import_data_rest_flattened(): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_delete_mirror_field_headers_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = mirror.DeleteMirrorRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/instances/sample3" - } + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_mirror), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.delete_mirror(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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.import_data(**mock_args) + # 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_mirror_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_mirror), "__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_mirror( + name="name_value", + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/instances/*}:importData" - % client.transport._host, - args[1], - ) + 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_import_data_rest_flattened_error(transport: str = "rest"): +def test_delete_mirror_flattened_error(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.import_data( - transfer.ImportDataRequest(), + client.delete_mirror( + mirror.DeleteMirrorRequest(), name="name_value", ) -def test_export_data_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.asyncio +async def test_delete_mirror_flattened_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.export_data in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_mirror), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + 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_mirror( + name="name_value", ) - client._transport._wrapped_methods[client._transport.export_data] = mock_rpc - - request = {} - client.export_data(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() + # Establish that 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 - client.export_data(request) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 +@pytest.mark.asyncio +async def test_delete_mirror_flattened_error_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_mirror( + mirror.DeleteMirrorRequest(), + name="name_value", + ) -def test_export_data_rest_required_fields(request_type=transfer.ExportDataRequest): - transport_class = transports.LustreRestTransport - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +@pytest.mark.parametrize( + "request_type", + [ + mirror.GetMirrorRequest(), + {}, + ], +) +def test_get_mirror(request_type, transport: str = "grpc"): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # verify fields with default values are dropped + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - default_values = getattr( - transport_class._BaseExportData, - "_BaseExportData__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_mirror), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = mirror.Mirror( + name="name_value", + direction=mirror.Mirror.Direction.FROM_CLOUD_STORAGE, + deleted_files_retained=True, + description="description_value", + uid="uid_value", + state=mirror.Mirror.State.CREATING, + ) + response = client.get_mirror(request) - # verify required fields with default values are now present + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = mirror.GetMirrorRequest() + assert args[0] == request - jsonified_request["name"] = "name_value" + # Establish that the response is the type that we expect. + assert isinstance(response, mirror.Mirror) + assert response.name == "name_value" + assert response.direction == mirror.Mirror.Direction.FROM_CLOUD_STORAGE + assert response.deleted_files_retained is True + assert response.description == "description_value" + assert response.uid == "uid_value" + assert response.state == mirror.Mirror.State.CREATING - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_get_mirror_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - 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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.export_data(request) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = mirror.GetMirrorRequest( + name="name_value", + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_mirror), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_mirror(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = mirror.GetMirrorRequest( + name="name_value", + ) + assert args[0] == request_msg -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.LustreGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): +def test_get_mirror_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.LustreGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LustreClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_mirror in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client._transport._wrapped_methods[client._transport.get_mirror] = mock_rpc + request = {} + client.get_mirror(request) - # It is an error to provide an api_key and a transport instance. - transport = transports.LustreGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LustreClient( - client_options=options, + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_mirror(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_mirror_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LustreClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # It is an error to provide scopes and a transport instance. - transport = transports.LustreGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LustreClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + # Ensure method has been cached + assert ( + client._client._transport.get_mirror + in client._client._transport._wrapped_methods ) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_mirror + ] = mock_rpc -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.LustreGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = LustreClient(transport=transport) - assert client.transport is transport + request = {} + await client.get_mirror(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.LustreGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + await client.get_mirror(request) - transport = transports.LustreGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 +@pytest.mark.asyncio @pytest.mark.parametrize( - "transport_class", + "request_type", [ - transports.LustreGrpcTransport, - transports.LustreGrpcAsyncIOTransport, - transports.LustreRestTransport, + mirror.GetMirrorRequest(), + {}, ], ) -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() +async def test_get_mirror_async(request_type, transport: str = "grpc_asyncio"): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type -def test_transport_kind_grpc(): - transport = LustreClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_mirror), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + mirror.Mirror( + name="name_value", + direction=mirror.Mirror.Direction.FROM_CLOUD_STORAGE, + deleted_files_retained=True, + description="description_value", + uid="uid_value", + state=mirror.Mirror.State.CREATING, + ) + ) + response = await client.get_mirror(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = mirror.GetMirrorRequest() + assert args[0] == request -def test_initialize_client_w_grpc(): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" - ) - assert client is not None + # Establish that the response is the type that we expect. + assert isinstance(response, mirror.Mirror) + assert response.name == "name_value" + assert response.direction == mirror.Mirror.Direction.FROM_CLOUD_STORAGE + assert response.deleted_files_retained is True + assert response.description == "description_value" + assert response.uid == "uid_value" + assert response.state == mirror.Mirror.State.CREATING -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_instances_empty_call_grpc(): +def test_get_mirror_field_headers(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: - call.return_value = instance.ListInstancesResponse() - client.list_instances(request=None) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = mirror.GetMirrorRequest() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = instance.ListInstancesRequest() - assert args[0] == request_msg + request.name = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_mirror), "__call__") as call: + call.return_value = mirror.Mirror() + client.get_mirror(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_instance_empty_call_grpc(): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_instance), "__call__") as call: - call.return_value = instance.Instance() - client.get_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = instance.GetInstanceRequest() - assert args[0] == request_msg + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_instance_empty_call_grpc(): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_get_mirror_field_headers_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcl_instance.CreateInstanceRequest() - assert args[0] == request_msg - + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = mirror.GetMirrorRequest() -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_instance_empty_call_grpc(): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + request.name = "name_value" - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_instance), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_instance(request=None) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_mirror), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mirror.Mirror()) + await client.get_mirror(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = gcl_instance.UpdateInstanceRequest() - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_instance_empty_call_grpc(): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_instance(request=None) + assert args[0] == request - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = instance.DeleteInstanceRequest() - assert args[0] == request_msg + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_import_data_empty_call_grpc(): +def test_get_mirror_flattened(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.import_data), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.import_data(request=None) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_mirror), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = mirror.Mirror() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_mirror( + name="name_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = transfer.ImportDataRequest() - assert args[0] == request_msg + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_export_data_empty_call_grpc(): +def test_get_mirror_flattened_error(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.export_data), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.export_data(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = transfer.ExportDataRequest() - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = LustreAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() ) - assert transport.kind == "grpc_asyncio" - -def test_initialize_client_w_grpc_asyncio(): - client = LustreAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" - ) - assert client is not None + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_mirror( + mirror.GetMirrorRequest(), + name="name_value", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_list_instances_empty_call_grpc_asyncio(): +async def test_get_mirror_flattened_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_mirror), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - instance.ListInstancesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + call.return_value = mirror.Mirror() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(mirror.Mirror()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_mirror( + name="name_value", ) - await client.list_instances(request=None) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = instance.ListInstancesRequest() - assert args[0] == request_msg + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_get_instance_empty_call_grpc_asyncio(): +async def test_get_mirror_flattened_error_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_mirror( + mirror.GetMirrorRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + mirror.ListMirrorsRequest(), + {}, + ], +) +def test_list_mirrors(request_type, transport: str = "grpc"): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mirrors), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - instance.Instance( - name="name_value", - filesystem="filesystem_value", - capacity_gib=1247, - network="network_value", - state=instance.Instance.State.ACTIVE, - mount_point="mount_point_value", - description="description_value", - per_unit_storage_throughput=2931, - gke_support_enabled=True, - ) + call.return_value = mirror.ListMirrorsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - await client.get_instance(request=None) + response = client.list_mirrors(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = instance.GetInstanceRequest() - assert args[0] == request_msg + request = mirror.ListMirrorsRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMirrorsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_instance_empty_call_grpc_asyncio(): - client = LustreAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +def test_list_mirrors_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.create_instance(request=None) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = mirror.ListMirrorsRequest( + parent="parent_value", + page_token="page_token_value", + order_by="order_by_value", + filter="filter_value", + ) - # Establish that the underlying stub method was called. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_mirrors), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_mirrors(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = gcl_instance.CreateInstanceRequest() + request_msg = mirror.ListMirrorsRequest( + parent="parent_value", + page_token="page_token_value", + order_by="order_by_value", + filter="filter_value", + ) assert args[0] == request_msg -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. +def test_list_mirrors_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_mirrors in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_mirrors] = mock_rpc + request = {} + client.list_mirrors(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_mirrors(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio -async def test_update_instance_empty_call_grpc_asyncio(): +async def test_list_mirrors_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_mirrors + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_mirrors + ] = mock_rpc + + request = {} + await client.list_mirrors(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_mirrors(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + mirror.ListMirrorsRequest(), + {}, + ], +) +async def test_list_mirrors_async(request_type, transport: str = "grpc_asyncio"): client = LustreAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_mirrors), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + mirror.ListMirrorsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) - await client.update_instance(request=None) + response = await client.list_mirrors(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = gcl_instance.UpdateInstanceRequest() - assert args[0] == request_msg + request = mirror.ListMirrorsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMirrorsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_mirrors_field_headers(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = mirror.ListMirrorsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_mirrors), "__call__") as call: + call.return_value = mirror.ListMirrorsResponse() + client.list_mirrors(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_delete_instance_empty_call_grpc_asyncio(): +async def test_list_mirrors_field_headers_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: - # Designate an appropriate return value for the call. + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = mirror.ListMirrorsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_mirrors), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + mirror.ListMirrorsResponse() ) - await client.delete_instance(request=None) + await client.list_mirrors(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = instance.DeleteInstanceRequest() - assert args[0] == request_msg + 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"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_import_data_empty_call_grpc_asyncio(): - client = LustreAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +def test_list_mirrors_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.import_data), "__call__") as call: + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_mirrors), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + call.return_value = mirror.ListMirrorsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_mirrors( + parent="parent_value", ) - await client.import_data(request=None) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = transfer.ImportDataRequest() - assert args[0] == request_msg + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_mirrors_flattened_error(): + client = LustreClient( + credentials=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_mirrors( + mirror.ListMirrorsRequest(), + parent="parent_value", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_export_data_empty_call_grpc_asyncio(): +async def test_list_mirrors_flattened_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.export_data), "__call__") as call: + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_mirrors), "__call__") as call: # Designate an appropriate return value for the call. + call.return_value = mirror.ListMirrorsResponse() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + mirror.ListMirrorsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_mirrors( + parent="parent_value", ) - await client.export_data(request=None) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = transfer.ExportDataRequest() - assert args[0] == request_msg + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -def test_transport_kind_rest(): - transport = LustreClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() +@pytest.mark.asyncio +async def test_list_mirrors_flattened_error_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), ) - assert transport.kind == "rest" + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_mirrors( + mirror.ListMirrorsRequest(), + parent="parent_value", + ) -def test_list_instances_rest_bad_request(request_type=instance.ListInstancesRequest): + +def test_list_mirrors_pager(transport_name: str = "grpc"): client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_instances(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_mirrors), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + mirror.ListMirrorsResponse( + mirrors=[ + mirror.Mirror(), + mirror.Mirror(), + mirror.Mirror(), + ], + next_page_token="abc", + ), + mirror.ListMirrorsResponse( + mirrors=[], + next_page_token="def", + ), + mirror.ListMirrorsResponse( + mirrors=[ + mirror.Mirror(), + ], + next_page_token="ghi", + ), + mirror.ListMirrorsResponse( + mirrors=[ + mirror.Mirror(), + mirror.Mirror(), + ], + ), + RuntimeError, + ) -@pytest.mark.parametrize( - "request_type", - [ - instance.ListInstancesRequest, - dict, - ], -) -def test_list_instances_rest_call_success(request_type): - client = LustreClient( - 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 = instance.ListInstancesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) + pager = client.list_mirrors(request={}, retry=retry, timeout=timeout) - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - # Convert return value to protobuf type - return_value = instance.ListInstancesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_instances(request) + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstancesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, mirror.Mirror) for i in results) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_instances_rest_interceptors(null_interceptor): - transport = transports.LustreRestTransport( +def test_list_mirrors_pages(transport_name: str = "grpc"): + client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + transport=transport_name, ) - client = LustreClient(transport=transport) - - with ( - mock.patch.object(type(client.transport._session), "request") as req, - mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object( - transports.LustreRestInterceptor, "post_list_instances" - ) as post, - mock.patch.object( - transports.LustreRestInterceptor, "post_list_instances_with_metadata" - ) as post_with_metadata, - mock.patch.object( - transports.LustreRestInterceptor, "pre_list_instances" - ) as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = instance.ListInstancesRequest.pb(instance.ListInstancesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = instance.ListInstancesResponse.to_json( - instance.ListInstancesResponse() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_mirrors), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + mirror.ListMirrorsResponse( + mirrors=[ + mirror.Mirror(), + mirror.Mirror(), + mirror.Mirror(), + ], + next_page_token="abc", + ), + mirror.ListMirrorsResponse( + mirrors=[], + next_page_token="def", + ), + mirror.ListMirrorsResponse( + mirrors=[ + mirror.Mirror(), + ], + next_page_token="ghi", + ), + mirror.ListMirrorsResponse( + mirrors=[ + mirror.Mirror(), + mirror.Mirror(), + ], + ), + RuntimeError, ) - req.return_value.content = return_value + pages = list(client.list_mirrors(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - request = instance.ListInstancesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = instance.ListInstancesResponse() - post_with_metadata.return_value = instance.ListInstancesResponse(), metadata - client.list_instances( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], +@pytest.mark.asyncio +async def test_list_mirrors_async_pager(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mirrors), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + mirror.ListMirrorsResponse( + mirrors=[ + mirror.Mirror(), + mirror.Mirror(), + mirror.Mirror(), + ], + next_page_token="abc", + ), + mirror.ListMirrorsResponse( + mirrors=[], + next_page_token="def", + ), + mirror.ListMirrorsResponse( + mirrors=[ + mirror.Mirror(), + ], + next_page_token="ghi", + ), + mirror.ListMirrorsResponse( + mirrors=[ + mirror.Mirror(), + mirror.Mirror(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_mirrors( + request={}, ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + assert len(responses) == 6 + assert all(isinstance(i, mirror.Mirror) for i in responses) -def test_get_instance_rest_bad_request(request_type=instance.GetInstanceRequest): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + +@pytest.mark.asyncio +async def test_list_mirrors_async_pages(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_instance(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mirrors), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + mirror.ListMirrorsResponse( + mirrors=[ + mirror.Mirror(), + mirror.Mirror(), + mirror.Mirror(), + ], + next_page_token="abc", + ), + mirror.ListMirrorsResponse( + mirrors=[], + next_page_token="def", + ), + mirror.ListMirrorsResponse( + mirrors=[ + mirror.Mirror(), + ], + next_page_token="ghi", + ), + mirror.ListMirrorsResponse( + mirrors=[ + mirror.Mirror(), + mirror.Mirror(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_mirrors(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", [ - instance.GetInstanceRequest, - dict, + gcl_directory_policy.CreateDirectoryPolicyRequest(), + {}, ], ) -def test_get_instance_rest_call_success(request_type): +def test_create_directory_policy(request_type, transport: str = "grpc"): client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = instance.Instance( - name="name_value", - filesystem="filesystem_value", - capacity_gib=1247, - network="network_value", - state=instance.Instance.State.ACTIVE, - mount_point="mount_point_value", - description="description_value", - per_unit_storage_throughput=2931, - gke_support_enabled=True, - ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_directory_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_directory_policy(request) - # Convert return value to protobuf type - return_value = instance.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_instance(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcl_directory_policy.CreateDirectoryPolicyRequest() + assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, instance.Instance) - assert response.name == "name_value" - assert response.filesystem == "filesystem_value" - assert response.capacity_gib == 1247 - assert response.network == "network_value" - assert response.state == instance.Instance.State.ACTIVE - assert response.mount_point == "mount_point_value" - assert response.description == "description_value" - assert response.per_unit_storage_throughput == 2931 - assert response.gke_support_enabled is True + assert isinstance(response, future.Future) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_instance_rest_interceptors(null_interceptor): - transport = transports.LustreRestTransport( +def test_create_directory_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + transport="grpc", ) - client = LustreClient(transport=transport) - with ( - mock.patch.object(type(client.transport._session), "request") as req, - mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object( - transports.LustreRestInterceptor, "post_get_instance" - ) as post, - mock.patch.object( - transports.LustreRestInterceptor, "post_get_instance_with_metadata" - ) as post_with_metadata, - mock.patch.object(transports.LustreRestInterceptor, "pre_get_instance") as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = instance.GetInstanceRequest.pb(instance.GetInstanceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcl_directory_policy.CreateDirectoryPolicyRequest( + parent="parent_value", + directory_policy_id="directory_policy_id_value", + ) - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = instance.Instance.to_json(instance.Instance()) - req.return_value.content = return_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_directory_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_directory_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcl_directory_policy.CreateDirectoryPolicyRequest( + parent="parent_value", + directory_policy_id="directory_policy_id_value", + ) + assert args[0] == request_msg - request = instance.GetInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = instance.Instance() - post_with_metadata.return_value = instance.Instance(), metadata - client.get_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], +def test_create_directory_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + # Ensure method has been cached + assert ( + client._transport.create_directory_policy + in client._transport._wrapped_methods + ) -def test_create_instance_rest_bad_request( - request_type=gcl_instance.CreateInstanceRequest, + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_directory_policy + ] = mock_rpc + request = {} + client.create_directory_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_directory_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_directory_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - client = LustreClient( - 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) + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_instance(request) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_directory_policy + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_directory_policy + ] = mock_rpc + + request = {} + await client.create_directory_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_directory_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 +@pytest.mark.asyncio @pytest.mark.parametrize( "request_type", [ - gcl_instance.CreateInstanceRequest, - dict, + gcl_directory_policy.CreateDirectoryPolicyRequest(), + {}, ], ) -def test_create_instance_rest_call_success(request_type): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +async def test_create_directory_policy_async( + request_type, transport: str = "grpc_asyncio" +): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["instance"] = { - "name": "name_value", - "filesystem": "filesystem_value", - "capacity_gib": 1247, - "network": "network_value", - "state": 1, - "mount_point": "mount_point_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "description": "description_value", - "labels": {}, - "per_unit_storage_throughput": 2931, - "gke_support_enabled": True, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - # Determine if the message type is proto-plus or protobuf - test_field = gcl_instance.CreateInstanceRequest.meta.fields["instance"] + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_directory_policy), "__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_directory_policy(request) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcl_directory_policy.CreateDirectoryPolicyRequest() + assert args[0] == request - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] +def test_create_directory_policy_field_headers(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) - subfields_not_in_runtime = [] + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcl_directory_policy.CreateDirectoryPolicyRequest() - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["instance"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value + request.parent = "parent_value" - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_directory_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_directory_policy(request) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["instance"][field])): - del request_init["instance"][field][i][subfield] - else: - del request_init["instance"][field][subfield] - request = request_type(**request_init) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_instance(request) - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +async def test_create_directory_policy_field_headers_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcl_directory_policy.CreateDirectoryPolicyRequest() -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_instance_rest_interceptors(null_interceptor): - transport = transports.LustreRestTransport( + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_directory_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_directory_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", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_directory_policy_flattened(): + client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LustreRestInterceptor(), ) - client = LustreClient(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.LustreRestInterceptor, "post_create_instance" - ) as post, - mock.patch.object( - transports.LustreRestInterceptor, "post_create_instance_with_metadata" - ) as post_with_metadata, - mock.patch.object( - transports.LustreRestInterceptor, "pre_create_instance" - ) as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gcl_instance.CreateInstanceRequest.pb( - gcl_instance.CreateInstanceRequest() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_directory_policy), "__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_directory_policy( + parent="parent_value", + directory_policy=gcl_directory_policy.DirectoryPolicy(name="name_value"), + directory_policy_id="directory_policy_id_value", ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value + # Establish that the 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].directory_policy + mock_val = gcl_directory_policy.DirectoryPolicy(name="name_value") + assert arg == mock_val + arg = args[0].directory_policy_id + mock_val = "directory_policy_id_value" + assert arg == mock_val - request = gcl_instance.CreateInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.create_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], +def test_create_directory_policy_flattened_error(): + client = LustreClient( + credentials=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_directory_policy( + gcl_directory_policy.CreateDirectoryPolicyRequest(), + parent="parent_value", + directory_policy=gcl_directory_policy.DirectoryPolicy(name="name_value"), + directory_policy_id="directory_policy_id_value", ) - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() +@pytest.mark.asyncio +async def test_create_directory_policy_flattened_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) -def test_update_instance_rest_bad_request( - request_type=gcl_instance.UpdateInstanceRequest, -): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_directory_policy), "__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_directory_policy( + parent="parent_value", + directory_policy=gcl_directory_policy.DirectoryPolicy(name="name_value"), + directory_policy_id="directory_policy_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].directory_policy + mock_val = gcl_directory_policy.DirectoryPolicy(name="name_value") + assert arg == mock_val + arg = args[0].directory_policy_id + mock_val = "directory_policy_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_directory_policy_flattened_error_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), ) - # send a request that will satisfy transcoding - request_init = { - "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} - } - request = request_type(**request_init) - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_instance(request) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_directory_policy( + gcl_directory_policy.CreateDirectoryPolicyRequest(), + parent="parent_value", + directory_policy=gcl_directory_policy.DirectoryPolicy(name="name_value"), + directory_policy_id="directory_policy_id_value", + ) @pytest.mark.parametrize( "request_type", [ - gcl_instance.UpdateInstanceRequest, - dict, + directory_policy.DeleteDirectoryPolicyRequest(), + {}, ], ) -def test_update_instance_rest_call_success(request_type): +def test_delete_directory_policy(request_type, transport: str = "grpc"): client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # send a request that will satisfy transcoding - request_init = { - "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} - } - request_init["instance"] = { - "name": "projects/sample1/locations/sample2/instances/sample3", - "filesystem": "filesystem_value", - "capacity_gib": 1247, - "network": "network_value", - "state": 1, - "mount_point": "mount_point_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "description": "description_value", - "labels": {}, - "per_unit_storage_throughput": 2931, - "gke_support_enabled": True, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - # Determine if the message type is proto-plus or protobuf - test_field = gcl_instance.UpdateInstanceRequest.meta.fields["instance"] + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_directory_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_directory_policy(request) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = directory_policy.DeleteDirectoryPolicyRequest() + assert args[0] == request - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] +def test_delete_directory_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - subfields_not_in_runtime = [] + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = directory_policy.DeleteDirectoryPolicyRequest( + name="name_value", + ) - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["instance"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_directory_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_directory_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = directory_policy.DeleteDirectoryPolicyRequest( + name="name_value", + ) + assert args[0] == request_msg - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["instance"][field])): - del request_init["instance"][field][i][subfield] - else: - del request_init["instance"][field][subfield] - request = request_type(**request_init) +def test_delete_directory_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_instance(request) + # Ensure method has been cached + assert ( + client._transport.delete_directory_policy + in client._transport._wrapped_methods + ) - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_directory_policy + ] = mock_rpc + request = {} + client.delete_directory_policy(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_instance_rest_interceptors(null_interceptor): - transport = transports.LustreRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LustreRestInterceptor(), - ) - client = LustreClient(transport=transport) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - 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.LustreRestInterceptor, "post_update_instance" - ) as post, - mock.patch.object( - transports.LustreRestInterceptor, "post_update_instance_with_metadata" - ) as post_with_metadata, - mock.patch.object( - transports.LustreRestInterceptor, "pre_update_instance" - ) as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gcl_instance.UpdateInstanceRequest.pb( - gcl_instance.UpdateInstanceRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } + client.delete_directory_policy(request) - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - request = gcl_instance.UpdateInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.update_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], +@pytest.mark.asyncio +async def test_delete_directory_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_directory_policy + in client._client._transport._wrapped_methods + ) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_directory_policy + ] = mock_rpc -def test_delete_instance_rest_bad_request(request_type=instance.DeleteInstanceRequest): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} - request = request_type(**request_init) + request = {} + await client.delete_directory_policy(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 = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_instance(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_directory_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 +@pytest.mark.asyncio @pytest.mark.parametrize( "request_type", [ - instance.DeleteInstanceRequest, - dict, + directory_policy.DeleteDirectoryPolicyRequest(), + {}, ], ) -def test_delete_instance_rest_call_success(request_type): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +async def test_delete_directory_policy_async( + request_type, transport: str = "grpc_asyncio" +): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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") + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_instance(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_directory_policy), "__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_directory_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = directory_policy.DeleteDirectoryPolicyRequest() + assert args[0] == request # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, future.Future) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_instance_rest_interceptors(null_interceptor): - transport = transports.LustreRestTransport( +def test_delete_directory_policy_field_headers(): + client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LustreRestInterceptor(), ) - client = LustreClient(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.LustreRestInterceptor, "post_delete_instance" - ) as post, - mock.patch.object( - transports.LustreRestInterceptor, "post_delete_instance_with_metadata" - ) as post_with_metadata, - mock.patch.object( - transports.LustreRestInterceptor, "pre_delete_instance" - ) as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = instance.DeleteInstanceRequest.pb(instance.DeleteInstanceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = directory_policy.DeleteDirectoryPolicyRequest() - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value + request.name = "name_value" - request = instance.DeleteInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_directory_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_directory_policy(request) - client.delete_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_directory_policy_field_headers_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = directory_policy.DeleteDirectoryPolicyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_directory_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) + await client.delete_directory_policy(request) - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_import_data_rest_bad_request(request_type=transfer.ImportDataRequest): +def test_delete_directory_policy_flattened(): client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.import_data(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_directory_policy), "__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_directory_policy( + 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_directory_policy_flattened_error(): + client = LustreClient( + credentials=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_directory_policy( + directory_policy.DeleteDirectoryPolicyRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_directory_policy_flattened_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_directory_policy), "__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_directory_policy( + 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_directory_policy_flattened_error_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_directory_policy( + directory_policy.DeleteDirectoryPolicyRequest(), + name="name_value", + ) @pytest.mark.parametrize( "request_type", [ - transfer.ImportDataRequest, - dict, + directory_policy.GetDirectoryPolicyRequest(), + {}, ], ) -def test_import_data_rest_call_success(request_type): +def test_get_directory_policy(request_type, transport: str = "grpc"): client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} - request = request_type(**request_init) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_directory_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = directory_policy.DirectoryPolicy( + name="name_value", + directory_path="directory_path_value", + lustre_project_id=1825, + uid="uid_value", + state=directory_policy.DirectoryPolicy.State.CREATING, + ) + response = client.get_directory_policy(request) - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.import_data(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = directory_policy.GetDirectoryPolicyRequest() + assert args[0] == request # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, directory_policy.DirectoryPolicy) + assert response.name == "name_value" + assert response.directory_path == "directory_path_value" + assert response.lustre_project_id == 1825 + assert response.uid == "uid_value" + assert response.state == directory_policy.DirectoryPolicy.State.CREATING -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_data_rest_interceptors(null_interceptor): - transport = transports.LustreRestTransport( +def test_get_directory_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + transport="grpc", ) - client = LustreClient(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.LustreRestInterceptor, "post_import_data") as post, - mock.patch.object( - transports.LustreRestInterceptor, "post_import_data_with_metadata" - ) as post_with_metadata, - mock.patch.object(transports.LustreRestInterceptor, "pre_import_data") as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = transfer.ImportDataRequest.pb(transfer.ImportDataRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = directory_policy.GetDirectoryPolicyRequest( + name="name_value", + ) - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_directory_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_directory_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = directory_policy.GetDirectoryPolicyRequest( + name="name_value", + ) + assert args[0] == request_msg - request = transfer.ImportDataRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.import_data( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], +def test_get_directory_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_directory_policy in client._transport._wrapped_methods + ) + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_directory_policy] = ( + mock_rpc + ) + request = {} + client.get_directory_policy(request) -def test_export_data_rest_bad_request(request_type=transfer.ExportDataRequest): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} - request = request_type(**request_init) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.export_data(request) + client.get_directory_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_directory_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_directory_policy + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_directory_policy + ] = mock_rpc + + request = {} + await client.get_directory_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_directory_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 +@pytest.mark.asyncio @pytest.mark.parametrize( "request_type", [ - transfer.ExportDataRequest, - dict, + directory_policy.GetDirectoryPolicyRequest(), + {}, ], ) -def test_export_data_rest_call_success(request_type): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +async def test_get_directory_policy_async( + request_type, transport: str = "grpc_asyncio" +): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} - request = request_type(**request_init) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_directory_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + directory_policy.DirectoryPolicy( + name="name_value", + directory_path="directory_path_value", + lustre_project_id=1825, + uid="uid_value", + state=directory_policy.DirectoryPolicy.State.CREATING, + ) + ) + response = await client.get_directory_policy(request) - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.export_data(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = directory_policy.GetDirectoryPolicyRequest() + assert args[0] == request # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, directory_policy.DirectoryPolicy) + assert response.name == "name_value" + assert response.directory_path == "directory_path_value" + assert response.lustre_project_id == 1825 + assert response.uid == "uid_value" + assert response.state == directory_policy.DirectoryPolicy.State.CREATING -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_data_rest_interceptors(null_interceptor): - transport = transports.LustreRestTransport( +def test_get_directory_policy_field_headers(): + client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LustreRestInterceptor(), ) - client = LustreClient(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.LustreRestInterceptor, "post_export_data") as post, - mock.patch.object( - transports.LustreRestInterceptor, "post_export_data_with_metadata" - ) as post_with_metadata, - mock.patch.object(transports.LustreRestInterceptor, "pre_export_data") as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = transfer.ExportDataRequest.pb(transfer.ExportDataRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = directory_policy.GetDirectoryPolicyRequest() - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value + request.name = "name_value" - request = transfer.ExportDataRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_directory_policy), "__call__" + ) as call: + call.return_value = directory_policy.DirectoryPolicy() + client.get_directory_policy(request) - client.export_data( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() + # 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_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_get_directory_policy_field_headers_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) - - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_location(request) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = directory_policy.GetDirectoryPolicyRequest() -@pytest.mark.parametrize( - "request_type", - [ - locations_pb2.GetLocationRequest, - dict, - ], -) -def test_get_location_rest(request_type): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {"name": "projects/sample1/locations/sample2"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + request.name = "name_value" - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_directory_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + directory_policy.DirectoryPolicy() + ) + await client.get_directory_policy(request) - response = client.get_location(request) + # Establish that 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, locations_pb2.Location) + # 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_list_locations_rest_bad_request( - request_type=locations_pb2.ListLocationsRequest, -): +def test_get_directory_policy_flattened(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type() - request = json_format.ParseDict({"name": "projects/sample1"}, request) - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_locations(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_directory_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = directory_policy.DirectoryPolicy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_directory_policy( + 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 -@pytest.mark.parametrize( - "request_type", - [ - locations_pb2.ListLocationsRequest, - dict, - ], -) -def test_list_locations_rest(request_type): +def test_get_directory_policy_flattened_error(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request_init = {"name": "projects/sample1"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_directory_policy( + directory_policy.GetDirectoryPolicyRequest(), + name="name_value", + ) - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} +@pytest.mark.asyncio +async def test_get_directory_policy_flattened_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) - response = client.list_locations(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_directory_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = directory_policy.DirectoryPolicy() - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + directory_policy.DirectoryPolicy() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_directory_policy( + 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 -def test_cancel_operation_rest_bad_request( - request_type=operations_pb2.CancelOperationRequest, -): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + +@pytest.mark.asyncio +async def test_get_directory_policy_flattened_error_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.cancel_operation(request) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_directory_policy( + directory_policy.GetDirectoryPolicyRequest(), + name="name_value", + ) @pytest.mark.parametrize( "request_type", [ - operations_pb2.CancelOperationRequest, - dict, + directory_policy.ListDirectoryPoliciesRequest(), + {}, ], ) -def test_cancel_operation_rest(request_type): +def test_list_directory_policies(request_type, transport: str = "grpc"): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = "{}" - response_value.content = json_return_value.encode("UTF-8") + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_directory_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = directory_policy.ListDirectoryPoliciesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_directory_policies(request) - 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] + request = directory_policy.ListDirectoryPoliciesRequest() + assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, pagers.ListDirectoryPoliciesPager) + assert response.next_page_token == "next_page_token_value" -def test_delete_operation_rest_bad_request( - request_type=operations_pb2.DeleteOperationRequest, -): +def test_list_directory_policies_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + transport="grpc", ) - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_operation(request) - + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = directory_policy.ListDirectoryPoliciesRequest( + parent="parent_value", + page_token="page_token_value", + ) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.DeleteOperationRequest, - dict, - ], -) -def test_delete_operation_rest(request_type): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # Designate an appropriate value for the returned response. - return_value = None + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_directory_policies), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_directory_policies(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = directory_policy.ListDirectoryPoliciesRequest( + parent="parent_value", + page_token="page_token_value", + ) + assert args[0] == request_msg - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = "{}" - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} +def test_list_directory_policies_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - response = client.delete_operation(request) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Establish that the response is the type that we expect. - assert response is None + # Ensure method has been cached + assert ( + client._transport.list_directory_policies + in client._transport._wrapped_methods + ) + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_directory_policies + ] = mock_rpc + request = {} + client.list_directory_policies(request) -def test_get_operation_rest_bad_request( - request_type=operations_pb2.GetOperationRequest, -): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_operation(request) + client.list_directory_policies(request) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() +@pytest.mark.asyncio +async def test_list_directory_policies_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Ensure method has been cached + assert ( + client._client._transport.list_directory_policies + in client._client._transport._wrapped_methods + ) - response = client.get_operation(request) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_directory_policies + ] = mock_rpc - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) + request = {} + await client.list_directory_policies(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -def test_list_operations_rest_bad_request( - request_type=operations_pb2.ListOperationsRequest, -): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) + await client.list_directory_policies(request) - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_operations(request) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 +@pytest.mark.asyncio @pytest.mark.parametrize( "request_type", [ - operations_pb2.ListOperationsRequest, - dict, + directory_policy.ListDirectoryPoliciesRequest(), + {}, ], ) -def test_list_operations_rest(request_type): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +async def test_list_directory_policies_async( + request_type, transport: str = "grpc_asyncio" +): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - request_init = {"name": "projects/sample1/locations/sample2"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_directory_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + directory_policy.ListDirectoryPoliciesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_directory_policies(request) - response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = directory_policy.ListDirectoryPoliciesRequest() + assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) + assert isinstance(response, pagers.ListDirectoryPoliciesAsyncPager) + assert response.next_page_token == "next_page_token_value" -def test_initialize_client_w_rest(): +def test_list_directory_policies_field_headers(): client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), ) - assert client is not None + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = directory_policy.ListDirectoryPoliciesRequest() -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_instances_empty_call_rest(): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + request.parent = "parent_value" - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: - client.list_instances(request=None) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_directory_policies), "__call__" + ) as call: + call.return_value = directory_policy.ListDirectoryPoliciesResponse() + client.list_directory_policies(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = instance.ListInstancesRequest() - assert args[0] == request_msg + 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"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_instance_empty_call_rest(): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_list_directory_policies_field_headers_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_instance), "__call__") as call: - client.get_instance(request=None) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = directory_policy.ListDirectoryPoliciesRequest() - # Establish that the underlying stub method was called. - call.assert_called() + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_directory_policies), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + directory_policy.ListDirectoryPoliciesResponse() + ) + await client.list_directory_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = instance.GetInstanceRequest() - assert args[0] == request_msg + 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"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_instance_empty_call_rest(): +def test_list_directory_policies_flattened(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: - client.create_instance(request=None) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_directory_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = directory_policy.ListDirectoryPoliciesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_directory_policies( + parent="parent_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = gcl_instance.CreateInstanceRequest() - assert args[0] == request_msg + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_instance_empty_call_rest(): +def test_list_directory_policies_flattened_error(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_instance), "__call__") as call: - client.update_instance(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcl_instance.UpdateInstanceRequest() - assert args[0] == request_msg + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_directory_policies( + directory_policy.ListDirectoryPoliciesRequest(), + parent="parent_value", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_instance_empty_call_rest(): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_list_directory_policies_flattened_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: - client.delete_instance(request=None) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_directory_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = directory_policy.ListDirectoryPoliciesResponse() - # Establish that the underlying stub method was called. - call.assert_called() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + directory_policy.ListDirectoryPoliciesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_directory_policies( + 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] - request_msg = instance.DeleteInstanceRequest() - assert args[0] == request_msg + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_import_data_empty_call_rest(): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_list_directory_policies_flattened_error_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.import_data), "__call__") as call: - client.import_data(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = transfer.ImportDataRequest() - assert args[0] == request_msg + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_directory_policies( + directory_policy.ListDirectoryPoliciesRequest(), + parent="parent_value", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_export_data_empty_call_rest(): +def test_list_directory_policies_pager(transport_name: str = "grpc"): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.export_data), "__call__") as call: - client.export_data(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = transfer.ExportDataRequest() - assert args[0] == request_msg + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_directory_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[ + directory_policy.DirectoryPolicy(), + directory_policy.DirectoryPolicy(), + directory_policy.DirectoryPolicy(), + ], + next_page_token="abc", + ), + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[], + next_page_token="def", + ), + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[ + directory_policy.DirectoryPolicy(), + ], + next_page_token="ghi", + ), + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[ + directory_policy.DirectoryPolicy(), + directory_policy.DirectoryPolicy(), + ], + ), + RuntimeError, + ) + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_directory_policies(request={}, retry=retry, timeout=timeout) -def test_lustre_rest_lro_client(): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - # Ensure that we have an api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, directory_policy.DirectoryPolicy) for i in results) -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_list_directory_policies_pages(transport_name: str = "grpc"): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - assert isinstance( - client.transport, - transports.LustreGrpcTransport, - ) - -def test_lustre_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.LustreTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_directory_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[ + directory_policy.DirectoryPolicy(), + directory_policy.DirectoryPolicy(), + directory_policy.DirectoryPolicy(), + ], + next_page_token="abc", + ), + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[], + next_page_token="def", + ), + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[ + directory_policy.DirectoryPolicy(), + ], + next_page_token="ghi", + ), + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[ + directory_policy.DirectoryPolicy(), + directory_policy.DirectoryPolicy(), + ], + ), + RuntimeError, ) + pages = list(client.list_directory_policies(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_lustre_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.lustre_v1.services.lustre.transports.LustreTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.LustreTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "list_instances", - "get_instance", - "create_instance", - "update_instance", - "delete_instance", - "import_data", - "export_data", - "get_location", - "list_locations", - "get_operation", - "cancel_operation", - "delete_operation", - "list_operations", +@pytest.mark.asyncio +async def test_list_directory_policies_async_pager(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), ) - 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_lustre_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.lustre_v1.services.lustre.transports.LustreTransport._prep_wrapped_messages" - ) as Transport, - ): - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LustreTransport( - credentials_file="credentials.json", - quota_project_id="octopus", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_directory_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[ + directory_policy.DirectoryPolicy(), + directory_policy.DirectoryPolicy(), + directory_policy.DirectoryPolicy(), + ], + next_page_token="abc", + ), + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[], + next_page_token="def", + ), + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[ + directory_policy.DirectoryPolicy(), + ], + next_page_token="ghi", + ), + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[ + directory_policy.DirectoryPolicy(), + directory_policy.DirectoryPolicy(), + ], + ), + RuntimeError, ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", + async_pager = await client.list_directory_policies( + request={}, ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) -def test_lustre_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.lustre_v1.services.lustre.transports.LustreTransport._prep_wrapped_messages" - ) as Transport, - ): - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LustreTransport() - adc.assert_called_once() + assert len(responses) == 6 + assert all(isinstance(i, directory_policy.DirectoryPolicy) for i in responses) -def test_lustre_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) - LustreClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id=None, +@pytest.mark.asyncio +async def test_list_directory_policies_async_pages(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_directory_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[ + directory_policy.DirectoryPolicy(), + directory_policy.DirectoryPolicy(), + directory_policy.DirectoryPolicy(), + ], + next_page_token="abc", + ), + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[], + next_page_token="def", + ), + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[ + directory_policy.DirectoryPolicy(), + ], + next_page_token="ghi", + ), + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[ + directory_policy.DirectoryPolicy(), + directory_policy.DirectoryPolicy(), + ], + ), + RuntimeError, ) + pages = [] + async for page_ in (await client.list_directory_policies(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( - "transport_class", - [ - transports.LustreGrpcTransport, - transports.LustreGrpcAsyncIOTransport, - ], -) -def test_lustre_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", +def test_list_instances_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "transport_class", - [ - transports.LustreGrpcTransport, - transports.LustreGrpcAsyncIOTransport, - transports.LustreRestTransport, - ], -) -def test_lustre_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) + # Ensure method has been cached + assert client._transport.list_instances in client._transport._wrapped_methods + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_instances] = mock_rpc -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.LustreGrpcTransport, grpc_helpers), - (transports.LustreGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -def test_lustre_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"]) + request = {} + client.list_instances(request) - create_channel.assert_called_with( - "lustre.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="lustre.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.list_instances(request) -@pytest.mark.parametrize( - "transport_class", - [transports.LustreGrpcTransport, transports.LustreGrpcAsyncIOTransport], -) -def test_lustre_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = ga_credentials.AnonymousCredentials() + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # 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_list_instances_rest_required_fields( + request_type=instance.ListInstancesRequest, +): + transport_class = transports.LustreRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListInstances, + "_BaseListInstances__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = instance.ListInstancesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_instances(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_instances_rest_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = instance.ListInstancesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = instance.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_instances(**mock_args) + + # Establish that the underlying call 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/*}/instances" % client.transport._host, + args[1], + ) + + +def test_list_instances_rest_flattened_error(transport: str = "rest"): + client = LustreClient( + credentials=ga_credentials.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_instances( + instance.ListInstancesRequest(), + parent="parent_value", + ) + + +def test_list_instances_rest_pager(transport: str = "rest"): + client = LustreClient( + 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 = ( + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + instance.Instance(), + ], + next_page_token="abc", + ), + instance.ListInstancesResponse( + instances=[], + next_page_token="def", + ), + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + ], + next_page_token="ghi", + ), + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(instance.ListInstancesResponse.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_instances(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, instance.Instance) for i in results) + + pages = list(client.list_instances(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_instance] = mock_rpc + + request = {} + client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_instance_rest_required_fields(request_type=instance.GetInstanceRequest): + transport_class = transports.LustreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetInstance, + "_BaseGetInstance__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = instance.Instance() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_instance_rest_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = instance.Instance() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = instance.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_instance(**mock_args) + + # Establish that the underlying call 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/*/instances/*}" % client.transport._host, + args[1], + ) + + +def test_get_instance_rest_flattened_error(transport: str = "rest"): + client = LustreClient( + credentials=ga_credentials.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_instance( + instance.GetInstanceRequest(), + name="name_value", + ) + + +def test_create_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_instance] = mock_rpc + + request = {} + client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_instance_rest_required_fields( + request_type=gcl_instance.CreateInstanceRequest, +): + transport_class = transports.LustreRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["instance_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "instanceId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateInstance, + "_BaseCreateInstance__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["instanceId"] = "instance_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "instanceId", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == "instance_id_value" + + client = LustreClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_instance(request) + + expected_params = [ + ( + "instanceId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_instance_rest_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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", + instance=gcl_instance.Instance(name="name_value"), + instance_id="instance_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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_instance(**mock_args) + + # Establish that the underlying call 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/*}/instances" % client.transport._host, + args[1], + ) + + +def test_create_instance_rest_flattened_error(transport: str = "rest"): + client = LustreClient( + credentials=ga_credentials.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_instance( + gcl_instance.CreateInstanceRequest(), + parent="parent_value", + instance=gcl_instance.Instance(name="name_value"), + instance_id="instance_id_value", + ) + + +def test_update_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_instance] = mock_rpc + + request = {} + client.update_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_instance_rest_required_fields( + request_type=gcl_instance.UpdateInstanceRequest, +): + transport_class = transports.LustreRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateInstance, + "_BaseUpdateInstance__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = LustreClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_instance_rest_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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 = { + "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + instance=gcl_instance.Instance(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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_instance(**mock_args) + + # Establish that the underlying call 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/{instance.name=projects/*/locations/*/instances/*}" + % client.transport._host, + args[1], + ) + + +def test_update_instance_rest_flattened_error(transport: str = "rest"): + client = LustreClient( + credentials=ga_credentials.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_instance( + gcl_instance.UpdateInstanceRequest(), + instance=gcl_instance.Instance(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_instance] = mock_rpc + + request = {} + client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_instance_rest_required_fields( + request_type=instance.DeleteInstanceRequest, +): + transport_class = transports.LustreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseDeleteInstance, + "_BaseDeleteInstance__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "force", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = LustreClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_instance_rest_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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/instances/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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_instance(**mock_args) + + # Establish that the underlying call 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/*/instances/*}" % client.transport._host, + args[1], + ) + + +def test_delete_instance_rest_flattened_error(transport: str = "rest"): + client = LustreClient( + credentials=ga_credentials.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_instance( + instance.DeleteInstanceRequest(), + name="name_value", + ) + + +def test_reschedule_maintenance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.reschedule_maintenance + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.reschedule_maintenance] = ( + mock_rpc + ) + + request = {} + client.reschedule_maintenance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.reschedule_maintenance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_reschedule_maintenance_rest_required_fields( + request_type=instance.RescheduleMaintenanceRequest, +): + transport_class = transports.LustreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseRescheduleMaintenance, + "_BaseRescheduleMaintenance__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = LustreClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.reschedule_maintenance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_reschedule_maintenance_rest_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + reschedule=instance.RescheduleMaintenanceRequest.Reschedule( + reschedule_type=instance.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE + ), + ) + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.reschedule_maintenance(**mock_args) + + # Establish that the underlying call 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/*/instances/*}:rescheduleMaintenance" + % client.transport._host, + args[1], + ) + + +def test_reschedule_maintenance_rest_flattened_error(transport: str = "rest"): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.reschedule_maintenance( + instance.RescheduleMaintenanceRequest(), + name="name_value", + reschedule=instance.RescheduleMaintenanceRequest.Reschedule( + reschedule_type=instance.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE + ), + ) + + +def test_import_data_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.import_data in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.import_data] = mock_rpc + + request = {} + client.import_data(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.import_data(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_import_data_rest_required_fields(request_type=transfer.ImportDataRequest): + transport_class = transports.LustreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseImportData, + "_BaseImportData__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = LustreClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.import_data(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_import_data_rest_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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/instances/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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.import_data(**mock_args) + + # Establish that the underlying call 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/*/instances/*}:importData" + % client.transport._host, + args[1], + ) + + +def test_import_data_rest_flattened_error(transport: str = "rest"): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.import_data( + transfer.ImportDataRequest(), + name="name_value", + ) + + +def test_export_data_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.export_data in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.export_data] = mock_rpc + + request = {} + client.export_data(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.export_data(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_export_data_rest_required_fields(request_type=transfer.ExportDataRequest): + transport_class = transports.LustreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseExportData, + "_BaseExportData__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = LustreClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.export_data(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_mirror_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_mirror in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_mirror] = mock_rpc + + request = {} + client.create_mirror(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_mirror(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_mirror_rest_required_fields( + request_type=gcl_mirror.CreateMirrorRequest, +): + transport_class = transports.LustreRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["mirror_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "mirrorId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateMirror, + "_BaseCreateMirror__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "mirrorId" in jsonified_request + assert jsonified_request["mirrorId"] == request_init["mirror_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["mirrorId"] = "mirror_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "mirrorId", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "mirrorId" in jsonified_request + assert jsonified_request["mirrorId"] == "mirror_id_value" + + client = LustreClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_mirror(request) + + expected_params = [ + ( + "mirrorId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_mirror_rest_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + mirror=gcl_mirror.Mirror(name="name_value"), + mirror_id="mirror_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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_mirror(**mock_args) + + # Establish that the underlying call 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/*/instances/*}/mirrors" + % client.transport._host, + args[1], + ) + + +def test_create_mirror_rest_flattened_error(transport: str = "rest"): + client = LustreClient( + credentials=ga_credentials.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_mirror( + gcl_mirror.CreateMirrorRequest(), + parent="parent_value", + mirror=gcl_mirror.Mirror(name="name_value"), + mirror_id="mirror_id_value", + ) + + +def test_update_mirror_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_mirror in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_mirror] = mock_rpc + + request = {} + client.update_mirror(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_mirror(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_mirror_rest_required_fields( + request_type=gcl_mirror.UpdateMirrorRequest, +): + transport_class = transports.LustreRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseUpdateMirror, + "_BaseUpdateMirror__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = LustreClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_mirror(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_mirror_rest_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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 = { + "mirror": { + "name": "projects/sample1/locations/sample2/instances/sample3/mirrors/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + mirror=gcl_mirror.Mirror(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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_mirror(**mock_args) + + # Establish that the underlying call 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/{mirror.name=projects/*/locations/*/instances/*/mirrors/*}" + % client.transport._host, + args[1], + ) + + +def test_update_mirror_rest_flattened_error(transport: str = "rest"): + client = LustreClient( + credentials=ga_credentials.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_mirror( + gcl_mirror.UpdateMirrorRequest(), + mirror=gcl_mirror.Mirror(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_mirror_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_mirror in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_mirror] = mock_rpc + + request = {} + client.delete_mirror(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_mirror(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_mirror_rest_required_fields(request_type=mirror.DeleteMirrorRequest): + transport_class = transports.LustreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseDeleteMirror, + "_BaseDeleteMirror__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("requestId",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = LustreClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_mirror(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_mirror_rest_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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/instances/sample3/mirrors/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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_mirror(**mock_args) + + # Establish that the underlying call 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/*/instances/*/mirrors/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_mirror_rest_flattened_error(transport: str = "rest"): + client = LustreClient( + credentials=ga_credentials.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_mirror( + mirror.DeleteMirrorRequest(), + name="name_value", + ) + + +def test_get_mirror_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_mirror in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_mirror] = mock_rpc + + request = {} + client.get_mirror(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_mirror(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_mirror_rest_required_fields(request_type=mirror.GetMirrorRequest): + transport_class = transports.LustreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetMirror, + "_BaseGetMirror__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = mirror.Mirror() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = mirror.Mirror.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_mirror(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_mirror_rest_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = mirror.Mirror() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3/mirrors/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = mirror.Mirror.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_mirror(**mock_args) + + # Establish that the underlying call 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/*/instances/*/mirrors/*}" + % client.transport._host, + args[1], + ) + + +def test_get_mirror_rest_flattened_error(transport: str = "rest"): + client = LustreClient( + credentials=ga_credentials.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_mirror( + mirror.GetMirrorRequest(), + name="name_value", + ) + + +def test_list_mirrors_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_mirrors in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_mirrors] = mock_rpc + + request = {} + client.list_mirrors(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_mirrors(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_mirrors_rest_required_fields(request_type=mirror.ListMirrorsRequest): + transport_class = transports.LustreRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListMirrors, + "_BaseListMirrors__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = mirror.ListMirrorsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = mirror.ListMirrorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_mirrors(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_mirrors_rest_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = mirror.ListMirrorsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = mirror.ListMirrorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_mirrors(**mock_args) + + # Establish that the underlying call 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/*/instances/*}/mirrors" + % client.transport._host, + args[1], + ) + + +def test_list_mirrors_rest_flattened_error(transport: str = "rest"): + client = LustreClient( + credentials=ga_credentials.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_mirrors( + mirror.ListMirrorsRequest(), + parent="parent_value", + ) + + +def test_list_mirrors_rest_pager(transport: str = "rest"): + client = LustreClient( + 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 = ( + mirror.ListMirrorsResponse( + mirrors=[ + mirror.Mirror(), + mirror.Mirror(), + mirror.Mirror(), + ], + next_page_token="abc", + ), + mirror.ListMirrorsResponse( + mirrors=[], + next_page_token="def", + ), + mirror.ListMirrorsResponse( + mirrors=[ + mirror.Mirror(), + ], + next_page_token="ghi", + ), + mirror.ListMirrorsResponse( + mirrors=[ + mirror.Mirror(), + mirror.Mirror(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(mirror.ListMirrorsResponse.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/instances/sample3" + } + + pager = client.list_mirrors(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, mirror.Mirror) for i in results) + + pages = list(client.list_mirrors(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_directory_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_directory_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_directory_policy + ] = mock_rpc + + request = {} + client.create_directory_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_directory_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_directory_policy_rest_required_fields( + request_type=gcl_directory_policy.CreateDirectoryPolicyRequest, +): + transport_class = transports.LustreRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["directory_policy_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "directoryPolicyId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateDirectoryPolicy, + "_BaseCreateDirectoryPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "directoryPolicyId" in jsonified_request + assert jsonified_request["directoryPolicyId"] == request_init["directory_policy_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["directoryPolicyId"] = "directory_policy_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("directoryPolicyId",)) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "directoryPolicyId" in jsonified_request + assert jsonified_request["directoryPolicyId"] == "directory_policy_id_value" + + client = LustreClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_directory_policy(request) + + expected_params = [ + ( + "directoryPolicyId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_directory_policy_rest_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + directory_policy=gcl_directory_policy.DirectoryPolicy(name="name_value"), + directory_policy_id="directory_policy_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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_directory_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/instances/*}/directoryPolicies" + % client.transport._host, + args[1], + ) + + +def test_create_directory_policy_rest_flattened_error(transport: str = "rest"): + client = LustreClient( + credentials=ga_credentials.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_directory_policy( + gcl_directory_policy.CreateDirectoryPolicyRequest(), + parent="parent_value", + directory_policy=gcl_directory_policy.DirectoryPolicy(name="name_value"), + directory_policy_id="directory_policy_id_value", + ) + + +def test_delete_directory_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_directory_policy + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_directory_policy + ] = mock_rpc + + request = {} + client.delete_directory_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_directory_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_directory_policy_rest_required_fields( + request_type=directory_policy.DeleteDirectoryPolicyRequest, +): + transport_class = transports.LustreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseDeleteDirectoryPolicy, + "_BaseDeleteDirectoryPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = LustreClient( + 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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_directory_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_directory_policy_rest_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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/instances/sample3/directoryPolicies/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 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_directory_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/instances/*/directoryPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_directory_policy_rest_flattened_error(transport: str = "rest"): + client = LustreClient( + credentials=ga_credentials.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_directory_policy( + directory_policy.DeleteDirectoryPolicyRequest(), + name="name_value", + ) + + +def test_get_directory_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_directory_policy in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_directory_policy] = ( + mock_rpc + ) + + request = {} + client.get_directory_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_directory_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_directory_policy_rest_required_fields( + request_type=directory_policy.GetDirectoryPolicyRequest, +): + transport_class = transports.LustreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetDirectoryPolicy, + "_BaseGetDirectoryPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = directory_policy.DirectoryPolicy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = directory_policy.DirectoryPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_directory_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_directory_policy_rest_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = directory_policy.DirectoryPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3/directoryPolicies/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = directory_policy.DirectoryPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_directory_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/instances/*/directoryPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_get_directory_policy_rest_flattened_error(transport: str = "rest"): + client = LustreClient( + credentials=ga_credentials.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_directory_policy( + directory_policy.GetDirectoryPolicyRequest(), + name="name_value", + ) + + +def test_list_directory_policies_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_directory_policies + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_directory_policies + ] = mock_rpc + + request = {} + client.list_directory_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_directory_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_directory_policies_rest_required_fields( + request_type=directory_policy.ListDirectoryPoliciesRequest, +): + transport_class = transports.LustreRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseListDirectoryPolicies, + "_BaseListDirectoryPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = directory_policy.ListDirectoryPoliciesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = directory_policy.ListDirectoryPoliciesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_directory_policies(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_directory_policies_rest_flattened(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = directory_policy.ListDirectoryPoliciesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = directory_policy.ListDirectoryPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_directory_policies(**mock_args) + + # Establish that the underlying call 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/*/instances/*}/directoryPolicies" + % client.transport._host, + args[1], + ) + + +def test_list_directory_policies_rest_flattened_error(transport: str = "rest"): + client = LustreClient( + credentials=ga_credentials.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_directory_policies( + directory_policy.ListDirectoryPoliciesRequest(), + parent="parent_value", + ) + + +def test_list_directory_policies_rest_pager(transport: str = "rest"): + client = LustreClient( + 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 = ( + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[ + directory_policy.DirectoryPolicy(), + directory_policy.DirectoryPolicy(), + directory_policy.DirectoryPolicy(), + ], + next_page_token="abc", + ), + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[], + next_page_token="def", + ), + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[ + directory_policy.DirectoryPolicy(), + ], + next_page_token="ghi", + ), + directory_policy.ListDirectoryPoliciesResponse( + directory_policies=[ + directory_policy.DirectoryPolicy(), + directory_policy.DirectoryPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + directory_policy.ListDirectoryPoliciesResponse.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/instances/sample3" + } + + pager = client.list_directory_policies(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, directory_policy.DirectoryPolicy) for i in results) + + pages = list(client.list_directory_policies(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.LustreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.LustreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LustreClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.LustreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LustreClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LustreClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.LustreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LustreClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.LustreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = LustreClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.LustreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.LustreGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LustreGrpcTransport, + transports.LustreGrpcAsyncIOTransport, + transports.LustreRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = LustreClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_instances_empty_call_grpc(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + call.return_value = instance.ListInstancesResponse() + client.list_instances(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.ListInstancesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_instance_empty_call_grpc(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + call.return_value = instance.Instance() + client.get_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.GetInstanceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_instance_empty_call_grpc(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcl_instance.CreateInstanceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_instance_empty_call_grpc(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcl_instance.UpdateInstanceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_instance_empty_call_grpc(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.DeleteInstanceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_reschedule_maintenance_empty_call_grpc(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.reschedule_maintenance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.RescheduleMaintenanceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_data_empty_call_grpc(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_data), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_data(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = transfer.ImportDataRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_data_empty_call_grpc(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_data), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_data(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = transfer.ExportDataRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_mirror_empty_call_grpc(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_mirror), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_mirror(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcl_mirror.CreateMirrorRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_mirror_empty_call_grpc(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_mirror), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_mirror(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcl_mirror.UpdateMirrorRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_mirror_empty_call_grpc(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_mirror), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_mirror(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = mirror.DeleteMirrorRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_mirror_empty_call_grpc(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_mirror), "__call__") as call: + call.return_value = mirror.Mirror() + client.get_mirror(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = mirror.GetMirrorRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_mirrors_empty_call_grpc(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_mirrors), "__call__") as call: + call.return_value = mirror.ListMirrorsResponse() + client.list_mirrors(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = mirror.ListMirrorsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_directory_policy_empty_call_grpc(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_directory_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_directory_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcl_directory_policy.CreateDirectoryPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_directory_policy_empty_call_grpc(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_directory_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_directory_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = directory_policy.DeleteDirectoryPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_directory_policy_empty_call_grpc(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_directory_policy), "__call__" + ) as call: + call.return_value = directory_policy.DirectoryPolicy() + client.get_directory_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = directory_policy.GetDirectoryPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_directory_policies_empty_call_grpc(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_directory_policies), "__call__" + ) as call: + call.return_value = directory_policy.ListDirectoryPoliciesResponse() + client.list_directory_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = directory_policy.ListDirectoryPoliciesRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = LustreAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_instances_empty_call_grpc_asyncio(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_instances(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.ListInstancesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_instance_empty_call_grpc_asyncio(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + instance.Instance( + name="name_value", + filesystem="filesystem_value", + capacity_gib=1247, + network="network_value", + state=instance.Instance.State.ACTIVE, + mount_point="mount_point_value", + description="description_value", + per_unit_storage_throughput=2931, + gke_support_enabled=True, + kms_key="kms_key_value", + state_reason="state_reason_value", + placement_policy="placement_policy_value", + uid="uid_value", + available_version="available_version_value", + target_version="target_version_value", + effective_version="effective_version_value", + ) + ) + await client.get_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.GetInstanceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_instance_empty_call_grpc_asyncio(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcl_instance.CreateInstanceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_instance_empty_call_grpc_asyncio(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcl_instance.UpdateInstanceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_instance_empty_call_grpc_asyncio(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.DeleteInstanceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_reschedule_maintenance_empty_call_grpc_asyncio(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.reschedule_maintenance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.RescheduleMaintenanceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_data_empty_call_grpc_asyncio(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_data), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.import_data(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = transfer.ImportDataRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_export_data_empty_call_grpc_asyncio(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_data), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.export_data(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = transfer.ExportDataRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_mirror_empty_call_grpc_asyncio(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_mirror), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_mirror(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcl_mirror.CreateMirrorRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_mirror_empty_call_grpc_asyncio(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_mirror), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_mirror(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcl_mirror.UpdateMirrorRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_mirror_empty_call_grpc_asyncio(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_mirror), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_mirror(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = mirror.DeleteMirrorRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_mirror_empty_call_grpc_asyncio(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_mirror), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + mirror.Mirror( + name="name_value", + direction=mirror.Mirror.Direction.FROM_CLOUD_STORAGE, + deleted_files_retained=True, + description="description_value", + uid="uid_value", + state=mirror.Mirror.State.CREATING, + ) + ) + await client.get_mirror(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = mirror.GetMirrorRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_mirrors_empty_call_grpc_asyncio(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_mirrors), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + mirror.ListMirrorsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_mirrors(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = mirror.ListMirrorsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_directory_policy_empty_call_grpc_asyncio(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_directory_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_directory_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcl_directory_policy.CreateDirectoryPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_directory_policy_empty_call_grpc_asyncio(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_directory_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_directory_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = directory_policy.DeleteDirectoryPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_directory_policy_empty_call_grpc_asyncio(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_directory_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + directory_policy.DirectoryPolicy( + name="name_value", + directory_path="directory_path_value", + lustre_project_id=1825, + uid="uid_value", + state=directory_policy.DirectoryPolicy.State.CREATING, + ) + ) + await client.get_directory_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = directory_policy.GetDirectoryPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_directory_policies_empty_call_grpc_asyncio(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_directory_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + directory_policy.ListDirectoryPoliciesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_directory_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = directory_policy.ListDirectoryPoliciesRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = LustreClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_instances_rest_bad_request(request_type=instance.ListInstancesRequest): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_instances(request) + + +@pytest.mark.parametrize( + "request_type", + [ + instance.ListInstancesRequest, + dict, + ], +) +def test_list_instances_rest_call_success(request_type): + client = LustreClient( + 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 = instance.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_instances(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_instances_rest_interceptors(null_interceptor): + transport = transports.LustreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + ) + client = LustreClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.LustreRestInterceptor, "post_list_instances" + ) as post, + mock.patch.object( + transports.LustreRestInterceptor, "post_list_instances_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.LustreRestInterceptor, "pre_list_instances" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = instance.ListInstancesRequest.pb(instance.ListInstancesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = instance.ListInstancesResponse.to_json( + instance.ListInstancesResponse() + ) + req.return_value.content = return_value + + request = instance.ListInstancesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = instance.ListInstancesResponse() + post_with_metadata.return_value = instance.ListInstancesResponse(), metadata + + client.list_instances( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_instance_rest_bad_request(request_type=instance.GetInstanceRequest): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + instance.GetInstanceRequest, + dict, + ], +) +def test_get_instance_rest_call_success(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = instance.Instance( + name="name_value", + filesystem="filesystem_value", + capacity_gib=1247, + network="network_value", + state=instance.Instance.State.ACTIVE, + mount_point="mount_point_value", + description="description_value", + per_unit_storage_throughput=2931, + gke_support_enabled=True, + kms_key="kms_key_value", + state_reason="state_reason_value", + placement_policy="placement_policy_value", + uid="uid_value", + available_version="available_version_value", + target_version="target_version_value", + effective_version="effective_version_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = instance.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_instance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, instance.Instance) + assert response.name == "name_value" + assert response.filesystem == "filesystem_value" + assert response.capacity_gib == 1247 + assert response.network == "network_value" + assert response.state == instance.Instance.State.ACTIVE + assert response.mount_point == "mount_point_value" + assert response.description == "description_value" + assert response.per_unit_storage_throughput == 2931 + assert response.gke_support_enabled is True + assert response.kms_key == "kms_key_value" + assert response.state_reason == "state_reason_value" + assert response.placement_policy == "placement_policy_value" + assert response.uid == "uid_value" + assert response.available_version == "available_version_value" + assert response.target_version == "target_version_value" + assert response.effective_version == "effective_version_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_rest_interceptors(null_interceptor): + transport = transports.LustreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + ) + client = LustreClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.LustreRestInterceptor, "post_get_instance" + ) as post, + mock.patch.object( + transports.LustreRestInterceptor, "post_get_instance_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.LustreRestInterceptor, "pre_get_instance") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = instance.GetInstanceRequest.pb(instance.GetInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = instance.Instance.to_json(instance.Instance()) + req.return_value.content = return_value + + request = instance.GetInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = instance.Instance() + post_with_metadata.return_value = instance.Instance(), metadata + + client.get_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_instance_rest_bad_request( + request_type=gcl_instance.CreateInstanceRequest, +): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcl_instance.CreateInstanceRequest, + dict, + ], +) +def test_create_instance_rest_call_success(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["instance"] = { + "name": "name_value", + "filesystem": "filesystem_value", + "capacity_gib": 1247, + "network": "network_value", + "state": 1, + "mount_point": "mount_point_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "description": "description_value", + "labels": {}, + "per_unit_storage_throughput": 2931, + "gke_support_enabled": True, + "kms_key": "kms_key_value", + "state_reason": "state_reason_value", + "placement_policy": "placement_policy_value", + "access_rules_options": { + "access_rules": [ + { + "name": "name_value", + "ip_address_ranges": [ + "ip_address_ranges_value1", + "ip_address_ranges_value2", + ], + "squash_mode": 1, + } + ], + "default_squash_mode": 1, + "default_squash_uid": 1914, + "default_squash_gid": 1900, + }, + "uid": "uid_value", + "maintenance_policy": { + "weekly_maintenance_windows": [ + { + "day_of_week": 1, + "start_time": { + "hours": 561, + "minutes": 773, + "seconds": 751, + "nanos": 543, + }, + } + ], + "maintenance_exclusion_window": [ + { + "start_date": {"year": 433, "month": 550, "day": 318}, + "end_date": {}, + "time": {}, + } + ], + }, + "upcoming_maintenance_schedule": {"start_time": {}, "end_time": {}}, + "dynamic_tier_options": {"mode": 1}, + "available_version": "available_version_value", + "target_version": "target_version_value", + "effective_version": "effective_version_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcl_instance.CreateInstanceRequest.meta.fields["instance"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["instance"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["instance"][field])): + del request_init["instance"][field][i][subfield] + else: + del request_init["instance"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_instance_rest_interceptors(null_interceptor): + transport = transports.LustreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + ) + client = LustreClient(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.LustreRestInterceptor, "post_create_instance" + ) as post, + mock.patch.object( + transports.LustreRestInterceptor, "post_create_instance_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.LustreRestInterceptor, "pre_create_instance" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcl_instance.CreateInstanceRequest.pb( + gcl_instance.CreateInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcl_instance.CreateInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_instance_rest_bad_request( + request_type=gcl_instance.UpdateInstanceRequest, +): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcl_instance.UpdateInstanceRequest, + dict, + ], +) +def test_update_instance_rest_call_success(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} + } + request_init["instance"] = { + "name": "projects/sample1/locations/sample2/instances/sample3", + "filesystem": "filesystem_value", + "capacity_gib": 1247, + "network": "network_value", + "state": 1, + "mount_point": "mount_point_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "description": "description_value", + "labels": {}, + "per_unit_storage_throughput": 2931, + "gke_support_enabled": True, + "kms_key": "kms_key_value", + "state_reason": "state_reason_value", + "placement_policy": "placement_policy_value", + "access_rules_options": { + "access_rules": [ + { + "name": "name_value", + "ip_address_ranges": [ + "ip_address_ranges_value1", + "ip_address_ranges_value2", + ], + "squash_mode": 1, + } + ], + "default_squash_mode": 1, + "default_squash_uid": 1914, + "default_squash_gid": 1900, + }, + "uid": "uid_value", + "maintenance_policy": { + "weekly_maintenance_windows": [ + { + "day_of_week": 1, + "start_time": { + "hours": 561, + "minutes": 773, + "seconds": 751, + "nanos": 543, + }, + } + ], + "maintenance_exclusion_window": [ + { + "start_date": {"year": 433, "month": 550, "day": 318}, + "end_date": {}, + "time": {}, + } + ], + }, + "upcoming_maintenance_schedule": {"start_time": {}, "end_time": {}}, + "dynamic_tier_options": {"mode": 1}, + "available_version": "available_version_value", + "target_version": "target_version_value", + "effective_version": "effective_version_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcl_instance.UpdateInstanceRequest.meta.fields["instance"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["instance"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["instance"][field])): + del request_init["instance"][field][i][subfield] + else: + del request_init["instance"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_instance_rest_interceptors(null_interceptor): + transport = transports.LustreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + ) + client = LustreClient(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.LustreRestInterceptor, "post_update_instance" + ) as post, + mock.patch.object( + transports.LustreRestInterceptor, "post_update_instance_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.LustreRestInterceptor, "pre_update_instance" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcl_instance.UpdateInstanceRequest.pb( + gcl_instance.UpdateInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcl_instance.UpdateInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_instance_rest_bad_request(request_type=instance.DeleteInstanceRequest): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + instance.DeleteInstanceRequest, + dict, + ], +) +def test_delete_instance_rest_call_success(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_instance_rest_interceptors(null_interceptor): + transport = transports.LustreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + ) + client = LustreClient(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.LustreRestInterceptor, "post_delete_instance" + ) as post, + mock.patch.object( + transports.LustreRestInterceptor, "post_delete_instance_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.LustreRestInterceptor, "pre_delete_instance" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = instance.DeleteInstanceRequest.pb(instance.DeleteInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = instance.DeleteInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_reschedule_maintenance_rest_bad_request( + request_type=instance.RescheduleMaintenanceRequest, +): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.reschedule_maintenance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + instance.RescheduleMaintenanceRequest, + dict, + ], +) +def test_reschedule_maintenance_rest_call_success(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.reschedule_maintenance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_reschedule_maintenance_rest_interceptors(null_interceptor): + transport = transports.LustreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + ) + client = LustreClient(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.LustreRestInterceptor, "post_reschedule_maintenance" + ) as post, + mock.patch.object( + transports.LustreRestInterceptor, + "post_reschedule_maintenance_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.LustreRestInterceptor, "pre_reschedule_maintenance" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = instance.RescheduleMaintenanceRequest.pb( + instance.RescheduleMaintenanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = instance.RescheduleMaintenanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.reschedule_maintenance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_import_data_rest_bad_request(request_type=transfer.ImportDataRequest): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.import_data(request) + + +@pytest.mark.parametrize( + "request_type", + [ + transfer.ImportDataRequest, + dict, + ], +) +def test_import_data_rest_call_success(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.import_data(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_data_rest_interceptors(null_interceptor): + transport = transports.LustreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + ) + client = LustreClient(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.LustreRestInterceptor, "post_import_data") as post, + mock.patch.object( + transports.LustreRestInterceptor, "post_import_data_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.LustreRestInterceptor, "pre_import_data") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = transfer.ImportDataRequest.pb(transfer.ImportDataRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = transfer.ImportDataRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.import_data( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_export_data_rest_bad_request(request_type=transfer.ExportDataRequest): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.export_data(request) + + +@pytest.mark.parametrize( + "request_type", + [ + transfer.ExportDataRequest, + dict, + ], +) +def test_export_data_rest_call_success(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.export_data(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_data_rest_interceptors(null_interceptor): + transport = transports.LustreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + ) + client = LustreClient(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.LustreRestInterceptor, "post_export_data") as post, + mock.patch.object( + transports.LustreRestInterceptor, "post_export_data_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.LustreRestInterceptor, "pre_export_data") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = transfer.ExportDataRequest.pb(transfer.ExportDataRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = transfer.ExportDataRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.export_data( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_mirror_rest_bad_request(request_type=gcl_mirror.CreateMirrorRequest): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_mirror(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcl_mirror.CreateMirrorRequest, + dict, + ], +) +def test_create_mirror_rest_call_success(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/instances/sample3"} + request_init["mirror"] = { + "name": "name_value", + "gcs_path": {"uri": "uri_value"}, + "lustre_path": {"path": "path_value"}, + "direction": 1, + "deleted_files_retained": True, + "description": "description_value", + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "uid": "uid_value", + "state": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcl_mirror.CreateMirrorRequest.meta.fields["mirror"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["mirror"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["mirror"][field])): + del request_init["mirror"][field][i][subfield] + else: + del request_init["mirror"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_mirror(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_mirror_rest_interceptors(null_interceptor): + transport = transports.LustreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + ) + client = LustreClient(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.LustreRestInterceptor, "post_create_mirror" + ) as post, + mock.patch.object( + transports.LustreRestInterceptor, "post_create_mirror_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.LustreRestInterceptor, "pre_create_mirror") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcl_mirror.CreateMirrorRequest.pb(gcl_mirror.CreateMirrorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcl_mirror.CreateMirrorRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_mirror( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_mirror_rest_bad_request(request_type=gcl_mirror.UpdateMirrorRequest): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "mirror": { + "name": "projects/sample1/locations/sample2/instances/sample3/mirrors/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_mirror(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcl_mirror.UpdateMirrorRequest, + dict, + ], +) +def test_update_mirror_rest_call_success(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "mirror": { + "name": "projects/sample1/locations/sample2/instances/sample3/mirrors/sample4" + } + } + request_init["mirror"] = { + "name": "projects/sample1/locations/sample2/instances/sample3/mirrors/sample4", + "gcs_path": {"uri": "uri_value"}, + "lustre_path": {"path": "path_value"}, + "direction": 1, + "deleted_files_retained": True, + "description": "description_value", + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "uid": "uid_value", + "state": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcl_mirror.UpdateMirrorRequest.meta.fields["mirror"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["mirror"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["mirror"][field])): + del request_init["mirror"][field][i][subfield] + else: + del request_init["mirror"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_mirror(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_mirror_rest_interceptors(null_interceptor): + transport = transports.LustreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + ) + client = LustreClient(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.LustreRestInterceptor, "post_update_mirror" + ) as post, + mock.patch.object( + transports.LustreRestInterceptor, "post_update_mirror_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.LustreRestInterceptor, "pre_update_mirror") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcl_mirror.UpdateMirrorRequest.pb(gcl_mirror.UpdateMirrorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcl_mirror.UpdateMirrorRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_mirror( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_mirror_rest_bad_request(request_type=mirror.DeleteMirrorRequest): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/mirrors/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_mirror(request) + + +@pytest.mark.parametrize( + "request_type", + [ + mirror.DeleteMirrorRequest, + dict, + ], +) +def test_delete_mirror_rest_call_success(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/mirrors/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 = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_mirror(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_mirror_rest_interceptors(null_interceptor): + transport = transports.LustreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + ) + client = LustreClient(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.LustreRestInterceptor, "post_delete_mirror" + ) as post, + mock.patch.object( + transports.LustreRestInterceptor, "post_delete_mirror_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.LustreRestInterceptor, "pre_delete_mirror") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = mirror.DeleteMirrorRequest.pb(mirror.DeleteMirrorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = mirror.DeleteMirrorRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_mirror( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_mirror_rest_bad_request(request_type=mirror.GetMirrorRequest): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/mirrors/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_mirror(request) + + +@pytest.mark.parametrize( + "request_type", + [ + mirror.GetMirrorRequest, + dict, + ], +) +def test_get_mirror_rest_call_success(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/mirrors/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 = mirror.Mirror( + name="name_value", + direction=mirror.Mirror.Direction.FROM_CLOUD_STORAGE, + deleted_files_retained=True, + description="description_value", + uid="uid_value", + state=mirror.Mirror.State.CREATING, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = mirror.Mirror.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_mirror(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, mirror.Mirror) + assert response.name == "name_value" + assert response.direction == mirror.Mirror.Direction.FROM_CLOUD_STORAGE + assert response.deleted_files_retained is True + assert response.description == "description_value" + assert response.uid == "uid_value" + assert response.state == mirror.Mirror.State.CREATING + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_mirror_rest_interceptors(null_interceptor): + transport = transports.LustreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + ) + client = LustreClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(transports.LustreRestInterceptor, "post_get_mirror") as post, + mock.patch.object( + transports.LustreRestInterceptor, "post_get_mirror_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.LustreRestInterceptor, "pre_get_mirror") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = mirror.GetMirrorRequest.pb(mirror.GetMirrorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = mirror.Mirror.to_json(mirror.Mirror()) + req.return_value.content = return_value + + request = mirror.GetMirrorRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = mirror.Mirror() + post_with_metadata.return_value = mirror.Mirror(), metadata + + client.get_mirror( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_mirrors_rest_bad_request(request_type=mirror.ListMirrorsRequest): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_mirrors(request) + + +@pytest.mark.parametrize( + "request_type", + [ + mirror.ListMirrorsRequest, + dict, + ], +) +def test_list_mirrors_rest_call_success(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/instances/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 = mirror.ListMirrorsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = mirror.ListMirrorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_mirrors(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMirrorsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_mirrors_rest_interceptors(null_interceptor): + transport = transports.LustreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + ) + client = LustreClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.LustreRestInterceptor, "post_list_mirrors" + ) as post, + mock.patch.object( + transports.LustreRestInterceptor, "post_list_mirrors_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.LustreRestInterceptor, "pre_list_mirrors") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = mirror.ListMirrorsRequest.pb(mirror.ListMirrorsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = mirror.ListMirrorsResponse.to_json(mirror.ListMirrorsResponse()) + req.return_value.content = return_value + + request = mirror.ListMirrorsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = mirror.ListMirrorsResponse() + post_with_metadata.return_value = mirror.ListMirrorsResponse(), metadata + + client.list_mirrors( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_directory_policy_rest_bad_request( + request_type=gcl_directory_policy.CreateDirectoryPolicyRequest, +): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_directory_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcl_directory_policy.CreateDirectoryPolicyRequest, + dict, + ], +) +def test_create_directory_policy_rest_call_success(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/instances/sample3"} + request_init["directory_policy"] = { + "name": "name_value", + "directory_path": "directory_path_value", + "lustre_project_id": 1825, + "uid": "uid_value", + "state": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcl_directory_policy.CreateDirectoryPolicyRequest.meta.fields[ + "directory_policy" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["directory_policy"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["directory_policy"][field])): + del request_init["directory_policy"][field][i][subfield] + else: + del request_init["directory_policy"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_directory_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_directory_policy_rest_interceptors(null_interceptor): + transport = transports.LustreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + ) + client = LustreClient(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.LustreRestInterceptor, "post_create_directory_policy" + ) as post, + mock.patch.object( + transports.LustreRestInterceptor, + "post_create_directory_policy_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.LustreRestInterceptor, "pre_create_directory_policy" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcl_directory_policy.CreateDirectoryPolicyRequest.pb( + gcl_directory_policy.CreateDirectoryPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcl_directory_policy.CreateDirectoryPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_directory_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_directory_policy_rest_bad_request( + request_type=directory_policy.DeleteDirectoryPolicyRequest, +): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/directoryPolicies/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_directory_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + directory_policy.DeleteDirectoryPolicyRequest, + dict, + ], +) +def test_delete_directory_policy_rest_call_success(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/directoryPolicies/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 = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_directory_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_directory_policy_rest_interceptors(null_interceptor): + transport = transports.LustreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + ) + client = LustreClient(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.LustreRestInterceptor, "post_delete_directory_policy" + ) as post, + mock.patch.object( + transports.LustreRestInterceptor, + "post_delete_directory_policy_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.LustreRestInterceptor, "pre_delete_directory_policy" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = directory_policy.DeleteDirectoryPolicyRequest.pb( + directory_policy.DeleteDirectoryPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = directory_policy.DeleteDirectoryPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_directory_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_directory_policy_rest_bad_request( + request_type=directory_policy.GetDirectoryPolicyRequest, +): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/directoryPolicies/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_directory_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + directory_policy.GetDirectoryPolicyRequest, + dict, + ], +) +def test_get_directory_policy_rest_call_success(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/directoryPolicies/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 = directory_policy.DirectoryPolicy( + name="name_value", + directory_path="directory_path_value", + lustre_project_id=1825, + uid="uid_value", + state=directory_policy.DirectoryPolicy.State.CREATING, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = directory_policy.DirectoryPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_directory_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, directory_policy.DirectoryPolicy) + assert response.name == "name_value" + assert response.directory_path == "directory_path_value" + assert response.lustre_project_id == 1825 + assert response.uid == "uid_value" + assert response.state == directory_policy.DirectoryPolicy.State.CREATING + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_directory_policy_rest_interceptors(null_interceptor): + transport = transports.LustreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + ) + client = LustreClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.LustreRestInterceptor, "post_get_directory_policy" + ) as post, + mock.patch.object( + transports.LustreRestInterceptor, "post_get_directory_policy_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.LustreRestInterceptor, "pre_get_directory_policy" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = directory_policy.GetDirectoryPolicyRequest.pb( + directory_policy.GetDirectoryPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = directory_policy.DirectoryPolicy.to_json( + directory_policy.DirectoryPolicy() + ) + req.return_value.content = return_value + + request = directory_policy.GetDirectoryPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = directory_policy.DirectoryPolicy() + post_with_metadata.return_value = directory_policy.DirectoryPolicy(), metadata + + client.get_directory_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_directory_policies_rest_bad_request( + request_type=directory_policy.ListDirectoryPoliciesRequest, +): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_directory_policies(request) + + +@pytest.mark.parametrize( + "request_type", + [ + directory_policy.ListDirectoryPoliciesRequest, + dict, + ], +) +def test_list_directory_policies_rest_call_success(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/instances/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 = directory_policy.ListDirectoryPoliciesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = directory_policy.ListDirectoryPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_directory_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDirectoryPoliciesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_directory_policies_rest_interceptors(null_interceptor): + transport = transports.LustreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LustreRestInterceptor(), + ) + client = LustreClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.LustreRestInterceptor, "post_list_directory_policies" + ) as post, + mock.patch.object( + transports.LustreRestInterceptor, + "post_list_directory_policies_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.LustreRestInterceptor, "pre_list_directory_policies" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = directory_policy.ListDirectoryPoliciesRequest.pb( + directory_policy.ListDirectoryPoliciesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = directory_policy.ListDirectoryPoliciesResponse.to_json( + directory_policy.ListDirectoryPoliciesResponse() + ) + req.return_value.content = return_value + + request = directory_policy.ListDirectoryPoliciesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = directory_policy.ListDirectoryPoliciesResponse() + post_with_metadata.return_value = ( + directory_policy.ListDirectoryPoliciesResponse(), + metadata, + ) + + client.list_directory_policies( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/instances/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/instances/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/instances/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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( + request_type=operations_pb2.CancelOperationRequest, +): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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( + request_type=operations_pb2.DeleteOperationRequest, +): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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( + request_type=operations_pb2.GetOperationRequest, +): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + 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( + request_type=operations_pb2.ListOperationsRequest, +): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_instances_empty_call_rest(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + client.list_instances(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.ListInstancesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_instance_empty_call_rest(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + client.get_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.GetInstanceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_instance_empty_call_rest(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + client.create_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcl_instance.CreateInstanceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_instance_empty_call_rest(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + client.update_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcl_instance.UpdateInstanceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_instance_empty_call_rest(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + client.delete_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.DeleteInstanceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_reschedule_maintenance_empty_call_rest(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: + client.reschedule_maintenance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = instance.RescheduleMaintenanceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_data_empty_call_rest(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_data), "__call__") as call: + client.import_data(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = transfer.ImportDataRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_data_empty_call_rest(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_data), "__call__") as call: + client.export_data(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = transfer.ExportDataRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_mirror_empty_call_rest(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_mirror), "__call__") as call: + client.create_mirror(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcl_mirror.CreateMirrorRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_mirror_empty_call_rest(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_mirror), "__call__") as call: + client.update_mirror(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcl_mirror.UpdateMirrorRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_mirror_empty_call_rest(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_mirror), "__call__") as call: + client.delete_mirror(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = mirror.DeleteMirrorRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_mirror_empty_call_rest(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_mirror), "__call__") as call: + client.get_mirror(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = mirror.GetMirrorRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_mirrors_empty_call_rest(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_mirrors), "__call__") as call: + client.list_mirrors(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = mirror.ListMirrorsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_directory_policy_empty_call_rest(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_directory_policy), "__call__" + ) as call: + client.create_directory_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcl_directory_policy.CreateDirectoryPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_directory_policy_empty_call_rest(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_directory_policy), "__call__" + ) as call: + client.delete_directory_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = directory_policy.DeleteDirectoryPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_directory_policy_empty_call_rest(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_directory_policy), "__call__" + ) as call: + client.get_directory_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = directory_policy.GetDirectoryPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_directory_policies_empty_call_rest(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_directory_policies), "__call__" + ) as call: + client.list_directory_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = directory_policy.ListDirectoryPoliciesRequest() + assert args[0] == request_msg + + +def test_lustre_rest_lro_client(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.LustreGrpcTransport, + ) + + +def test_lustre_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.LustreTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_lustre_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.lustre_v1.services.lustre.transports.LustreTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.LustreTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_instances", + "get_instance", + "create_instance", + "update_instance", + "delete_instance", + "reschedule_maintenance", + "import_data", + "export_data", + "create_mirror", + "update_mirror", + "delete_mirror", + "get_mirror", + "list_mirrors", + "create_directory_policy", + "delete_directory_policy", + "get_directory_policy", + "list_directory_policies", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + "get_location", + "list_locations", + "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_lustre_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.lustre_v1.services.lustre.transports.LustreTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LustreTransport( + 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_lustre_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.lustre_v1.services.lustre.transports.LustreTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LustreTransport() + adc.assert_called_once() + + +def test_lustre_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) + LustreClient() + 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.LustreGrpcTransport, + transports.LustreGrpcAsyncIOTransport, + ], +) +def test_lustre_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.LustreGrpcTransport, + transports.LustreGrpcAsyncIOTransport, + transports.LustreRestTransport, + ], +) +def test_lustre_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.LustreGrpcTransport, grpc_helpers), + (transports.LustreGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_lustre_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( + "lustre.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="lustre.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.LustreGrpcTransport, transports.LustreGrpcAsyncIOTransport], +) +def test_lustre_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_lustre_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.LustreRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_lustre_host_no_port(transport_name): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="lustre.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "lustre.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://lustre.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_lustre_host_with_port(transport_name): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="lustre.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "lustre.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://lustre.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_lustre_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = LustreClient( + credentials=creds1, + transport=transport_name, + ) + client2 = LustreClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_instances._session + session2 = client2.transport.list_instances._session + assert session1 != session2 + session1 = client1.transport.get_instance._session + session2 = client2.transport.get_instance._session + assert session1 != session2 + session1 = client1.transport.create_instance._session + session2 = client2.transport.create_instance._session + assert session1 != session2 + session1 = client1.transport.update_instance._session + session2 = client2.transport.update_instance._session + assert session1 != session2 + session1 = client1.transport.delete_instance._session + session2 = client2.transport.delete_instance._session + assert session1 != session2 + session1 = client1.transport.reschedule_maintenance._session + session2 = client2.transport.reschedule_maintenance._session + assert session1 != session2 + session1 = client1.transport.import_data._session + session2 = client2.transport.import_data._session + assert session1 != session2 + session1 = client1.transport.export_data._session + session2 = client2.transport.export_data._session + assert session1 != session2 + session1 = client1.transport.create_mirror._session + session2 = client2.transport.create_mirror._session + assert session1 != session2 + session1 = client1.transport.update_mirror._session + session2 = client2.transport.update_mirror._session + assert session1 != session2 + session1 = client1.transport.delete_mirror._session + session2 = client2.transport.delete_mirror._session + assert session1 != session2 + session1 = client1.transport.get_mirror._session + session2 = client2.transport.get_mirror._session + assert session1 != session2 + session1 = client1.transport.list_mirrors._session + session2 = client2.transport.list_mirrors._session + assert session1 != session2 + session1 = client1.transport.create_directory_policy._session + session2 = client2.transport.create_directory_policy._session + assert session1 != session2 + session1 = client1.transport.delete_directory_policy._session + session2 = client2.transport.delete_directory_policy._session + assert session1 != session2 + session1 = client1.transport.get_directory_policy._session + session2 = client2.transport.get_directory_policy._session + assert session1 != session2 + session1 = client1.transport.list_directory_policies._session + session2 = client2.transport.list_directory_policies._session + assert session1 != session2 + + +def test_lustre_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LustreGrpcTransport( + 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_lustre_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LustreGrpcAsyncIOTransport( + 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.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [transports.LustreGrpcTransport, transports.LustreGrpcAsyncIOTransport], +) +def test_lustre_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.LustreGrpcTransport, transports.LustreGrpcAsyncIOTransport], +) +def test_lustre_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_lustre_grpc_lro_client(): + client = LustreClient( + 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_lustre_grpc_lro_async_client(): + client = LustreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_crypto_key_path(): + project = "squid" + location = "clam" + key_ring = "whelk" + crypto_key = "octopus" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + ) + actual = LustreClient.crypto_key_path(project, location, key_ring, crypto_key) + assert expected == actual + + +def test_parse_crypto_key_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "key_ring": "cuttlefish", + "crypto_key": "mussel", + } + path = LustreClient.crypto_key_path(**expected) + + # Check that the path construction is reversible. + actual = LustreClient.parse_crypto_key_path(path) + assert expected == actual + + +def test_directory_policy_path(): + project = "winkle" + location = "nautilus" + instance = "scallop" + directory_policy = "abalone" + expected = "projects/{project}/locations/{location}/instances/{instance}/directoryPolicies/{directory_policy}".format( + project=project, + location=location, + instance=instance, + directory_policy=directory_policy, + ) + actual = LustreClient.directory_policy_path( + project, location, instance, directory_policy + ) + assert expected == actual + + +def test_parse_directory_policy_path(): + expected = { + "project": "squid", + "location": "clam", + "instance": "whelk", + "directory_policy": "octopus", + } + path = LustreClient.directory_policy_path(**expected) + + # Check that the path construction is reversible. + actual = LustreClient.parse_directory_policy_path(path) + assert expected == actual + + +def test_instance_path(): + project = "oyster" + location = "nudibranch" + instance = "cuttlefish" + expected = "projects/{project}/locations/{location}/instances/{instance}".format( + project=project, + location=location, + instance=instance, + ) + actual = LustreClient.instance_path(project, location, instance) + assert expected == actual + + +def test_parse_instance_path(): + expected = { + "project": "mussel", + "location": "winkle", + "instance": "nautilus", + } + path = LustreClient.instance_path(**expected) + + # Check that the path construction is reversible. + actual = LustreClient.parse_instance_path(path) + assert expected == actual + + +def test_mirror_path(): + project = "scallop" + location = "abalone" + instance = "squid" + mirror = "clam" + expected = "projects/{project}/locations/{location}/instances/{instance}/mirrors/{mirror}".format( + project=project, + location=location, + instance=instance, + mirror=mirror, + ) + actual = LustreClient.mirror_path(project, location, instance, mirror) + assert expected == actual + + +def test_parse_mirror_path(): + expected = { + "project": "whelk", + "location": "octopus", + "instance": "oyster", + "mirror": "nudibranch", + } + path = LustreClient.mirror_path(**expected) + + # Check that the path construction is reversible. + actual = LustreClient.parse_mirror_path(path) + assert expected == actual + + +def test_network_path(): + project = "cuttlefish" + network = "mussel" + expected = "projects/{project}/global/networks/{network}".format( + project=project, + network=network, + ) + actual = LustreClient.network_path(project, network) + assert expected == actual + + +def test_parse_network_path(): + expected = { + "project": "winkle", + "network": "nautilus", + } + path = LustreClient.network_path(**expected) + + # Check that the path construction is reversible. + actual = LustreClient.parse_network_path(path) + assert expected == actual + + +def test_resource_policy_path(): + project = "scallop" + region = "abalone" + resource_policy = "squid" + expected = ( + "projects/{project}/regions/{region}/resourcePolicies/{resource_policy}".format( + project=project, + region=region, + resource_policy=resource_policy, + ) + ) + actual = LustreClient.resource_policy_path(project, region, resource_policy) + assert expected == actual + + +def test_parse_resource_policy_path(): + expected = { + "project": "clam", + "region": "whelk", + "resource_policy": "octopus", + } + path = LustreClient.resource_policy_path(**expected) + + # Check that the path construction is reversible. + actual = LustreClient.parse_resource_policy_path(path) + assert expected == actual + + +def test_service_account_path(): + project = "oyster" + service_account = "nudibranch" + expected = "projects/{project}/serviceAccounts/{service_account}".format( + project=project, + service_account=service_account, + ) + actual = LustreClient.service_account_path(project, service_account) + assert expected == actual + + +def test_parse_service_account_path(): + expected = { + "project": "cuttlefish", + "service_account": "mussel", + } + path = LustreClient.service_account_path(**expected) + + # Check that the path construction is reversible. + actual = LustreClient.parse_service_account_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = LustreClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = LustreClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = LustreClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = LustreClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = LustreClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = LustreClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = LustreClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = LustreClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = LustreClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format( + project=project, + ) + actual = LustreClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = LustreClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = LustreClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = LustreClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = LustreClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = LustreClient.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.LustreTransport, "_prep_wrapped_messages" + ) as prep: + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) -def test_lustre_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.LustreRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + with mock.patch.object( + transports.LustreTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = LustreClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + prep.assert_called_once_with(client_info) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_lustre_host_no_port(transport_name): +def test_delete_operation(transport: str = "grpc"): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="lustre.googleapis.com" - ), - transport=transport_name, + transport=transport, ) - assert client.transport._host == ( - "lustre.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://lustre.googleapis.com" + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_lustre_host_with_port(transport_name): + # 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 = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="lustre.googleapis.com:8000" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "lustre.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://lustre.googleapis.com:8000" ) + # Any value 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" -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) -def test_lustre_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = LustreClient( - credentials=creds1, - transport=transport_name, - ) - client2 = LustreClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_instances._session - session2 = client2.transport.list_instances._session - assert session1 != session2 - session1 = client1.transport.get_instance._session - session2 = client2.transport.get_instance._session - assert session1 != session2 - session1 = client1.transport.create_instance._session - session2 = client2.transport.create_instance._session - assert session1 != session2 - session1 = client1.transport.update_instance._session - session2 = client2.transport.update_instance._session - assert session1 != session2 - session1 = client1.transport.delete_instance._session - session2 = client2.transport.delete_instance._session - assert session1 != session2 - session1 = client1.transport.import_data._session - session2 = client2.transport.import_data._session - assert session1 != session2 - session1 = client1.transport.export_data._session - session2 = client2.transport.export_data._session - assert session1 != session2 + # 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"] -def test_lustre_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) - # Check that channel is used if provided. - transport = transports.LustreGrpcTransport( - host="squid.clam.whelk", - channel=channel, +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # Any value 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" -def test_lustre_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + # 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 - # Check that channel is used if provided. - transport = transports.LustreGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.filterwarnings("ignore::FutureWarning") -@pytest.mark.parametrize( - "transport_class", - [transports.LustreGrpcTransport, transports.LustreGrpcAsyncIOTransport], -) -def test_lustre_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 +def test_delete_operation_from_dict(): + client = LustreClient( + 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 - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() - 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 +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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() -# 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.LustreGrpcTransport, transports.LustreGrpcAsyncIOTransport], -) -def test_lustre_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() +def test_delete_operation_flattened(): + client = LustreClient( + 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 - 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, - ) + client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() - 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 + +@pytest.mark.asyncio +async def test_delete_operation_flattened_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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) + await client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() -def test_lustre_grpc_lro_client(): +def test_cancel_operation(transport: str = "grpc"): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) + # Everything is optional 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() - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # 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 -def test_lustre_grpc_lro_async_client(): +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): client = LustreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + credentials=async_anonymous_credentials(), + transport=transport, ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) + # Everything is optional 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() - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # 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_instance_path(): - project = "squid" - location = "clam" - instance = "whelk" - expected = "projects/{project}/locations/{location}/instances/{instance}".format( - project=project, - location=location, - instance=instance, + +def test_cancel_operation_field_headers(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), ) - actual = LustreClient.instance_path(project, location, instance) - assert expected == actual + # Any value 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" -def test_parse_instance_path(): - expected = { - "project": "octopus", - "location": "oyster", - "instance": "nudibranch", - } - path = LustreClient.instance_path(**expected) + # 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 - # Check that the path construction is reversible. - actual = LustreClient.parse_instance_path(path) - assert expected == actual + 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_network_path(): - project = "cuttlefish" - network = "mussel" - expected = "projects/{project}/global/networks/{network}".format( - project=project, - network=network, + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), ) - actual = LustreClient.network_path(project, network) - assert expected == actual + # Any value 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" -def test_parse_network_path(): - expected = { - "project": "winkle", - "network": "nautilus", - } - path = LustreClient.network_path(**expected) + # 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 - # Check that the path construction is reversible. - actual = LustreClient.parse_network_path(path) - assert expected == actual + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] -def test_service_account_path(): - project = "scallop" - service_account = "abalone" - expected = "projects/{project}/serviceAccounts/{service_account}".format( - project=project, - service_account=service_account, +def test_cancel_operation_from_dict(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), ) - actual = LustreClient.service_account_path(project, service_account) - assert expected == actual + # 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 = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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_cancel_operation_flattened(): + client = LustreClient( + 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 + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() -def test_parse_service_account_path(): - expected = { - "project": "squid", - "service_account": "clam", - } - path = LustreClient.service_account_path(**expected) - # Check that the path construction is reversible. - actual = LustreClient.parse_service_account_path(path) - assert expected == actual +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, +def test_get_operation(transport: str = "grpc"): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - actual = LustreClient.common_billing_account_path(billing_account) - assert expected == actual + # Everything is optional 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() -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = LustreClient.common_billing_account_path(**expected) + # 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 - # Check that the path construction is reversible. - actual = LustreClient.parse_common_billing_account_path(path) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format( - folder=folder, +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - actual = LustreClient.common_folder_path(folder) - assert expected == actual + # Everything is optional 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() -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = LustreClient.common_folder_path(**expected) + # 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 - # Check that the path construction is reversible. - actual = LustreClient.parse_common_folder_path(path) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format( - organization=organization, +def test_get_operation_field_headers(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), ) - actual = LustreClient.common_organization_path(organization) - assert expected == actual + # Any value 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" -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = LustreClient.common_organization_path(**expected) + # 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() - # Check that the path construction is reversible. - actual = LustreClient.parse_common_organization_path(path) - assert expected == actual + 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_common_project_path(): - project = "winkle" - expected = "projects/{project}".format( - project=project, +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), ) - actual = LustreClient.common_project_path(project) - assert expected == actual + # Any value 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" -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = LustreClient.common_project_path(**expected) + # 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 - # Check that the path construction is reversible. - actual = LustreClient.parse_common_project_path(path) - assert expected == actual + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, +def test_get_operation_from_dict(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), ) - actual = LustreClient.common_location_path(project, location) - assert expected == actual + # 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() -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = LustreClient.common_location_path(**expected) - # Check that the path construction is reversible. - actual = LustreClient.parse_common_location_path(path) - assert expected == actual +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() +def test_get_operation_flattened(): + client = LustreClient( + 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() - with mock.patch.object( - transports.LustreTransport, "_prep_wrapped_messages" - ) as prep: - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() - with mock.patch.object( - transports.LustreTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = LustreClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() ) - prep.assert_called_once_with(client_info) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() -def test_delete_operation(transport: str = "grpc"): +def test_list_operations(transport: str = "grpc"): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7434,24 +16464,24 @@ def test_delete_operation(transport: str = "grpc"): # Everything is optional 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() + request = operations_pb2.ListOperationsRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_operation(request) + 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 response is None + assert isinstance(response, operations_pb2.ListOperationsResponse) @pytest.mark.asyncio -async def test_delete_operation_async(transport: str = "grpc_asyncio"): +async def test_list_operations_async(transport: str = "grpc_asyncio"): client = LustreAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -7459,37 +16489,39 @@ async def test_delete_operation_async(transport: str = "grpc_asyncio"): # Everything is optional 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() + request = operations_pb2.ListOperationsRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + 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(None) - response = await client.delete_operation(request) + 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 response is None + assert isinstance(response, operations_pb2.ListOperationsResponse) -def test_delete_operation_field_headers(): +def test_list_operations_field_headers(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value 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 = 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.delete_operation), "__call__") as call: - call.return_value = None + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() - client.delete_operation(request) + client.list_operations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] @@ -7504,20 +16536,22 @@ def test_delete_operation_field_headers(): @pytest.mark.asyncio -async def test_delete_operation_field_headers_async(): +async def test_list_operations_field_headers_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = operations_pb2.DeleteOperationRequest() + 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.delete_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_operation(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] @@ -7531,16 +16565,16 @@ async def test_delete_operation_field_headers_async(): ) in kw["metadata"] -def test_delete_operation_from_dict(): +def test_list_operations_from_dict(): client = LustreClient( 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: + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = operations_pb2.ListOperationsResponse() - response = client.delete_operation( + response = client.list_operations( request={ "name": "locations", } @@ -7549,15 +16583,17 @@ def test_delete_operation_from_dict(): @pytest.mark.asyncio -async def test_delete_operation_from_dict_async(): +async def test_list_operations_from_dict_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + 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(None) - response = await client.delete_operation( + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( request={ "name": "locations", } @@ -7565,39 +16601,41 @@ async def test_delete_operation_from_dict_async(): call.assert_called() -def test_delete_operation_flattened(): +def test_list_operations_flattened(): client = LustreClient( 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: + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = operations_pb2.ListOperationsResponse() - client.delete_operation() + client.list_operations() # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.DeleteOperationRequest() + assert args[0] == operations_pb2.ListOperationsRequest() @pytest.mark.asyncio -async def test_delete_operation_flattened_async(): +async def test_list_operations_flattened_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + 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(None) - await client.delete_operation() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations() # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.DeleteOperationRequest() + assert args[0] == operations_pb2.ListOperationsRequest() -def test_cancel_operation(transport: str = "grpc"): +def test_list_locations(transport: str = "grpc"): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7605,24 +16643,24 @@ def test_cancel_operation(transport: str = "grpc"): # Everything is optional 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() + request = locations_pb2.ListLocationsRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(request) + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, locations_pb2.ListLocationsResponse) @pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc_asyncio"): +async def test_list_locations_async(transport: str = "grpc_asyncio"): client = LustreAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -7630,37 +16668,39 @@ async def test_cancel_operation_async(transport: str = "grpc_asyncio"): # Everything is optional 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() + request = locations_pb2.ListLocationsRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.cancel_operation(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, locations_pb2.ListLocationsResponse) -def test_cancel_operation_field_headers(): +def test_list_locations_field_headers(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value 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 = locations_pb2.ListLocationsRequest() request.name = "locations" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() - client.cancel_operation(request) + client.list_locations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] @@ -7675,20 +16715,22 @@ def test_cancel_operation_field_headers(): @pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): +async def test_list_locations_field_headers_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() + request = locations_pb2.ListLocationsRequest() request.name = "locations" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.cancel_operation(request) + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] @@ -7702,16 +16744,16 @@ async def test_cancel_operation_field_headers_async(): ) in kw["metadata"] -def test_cancel_operation_from_dict(): +def test_list_locations_from_dict(): client = LustreClient( 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: + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = locations_pb2.ListLocationsResponse() - response = client.cancel_operation( + response = client.list_locations( request={ "name": "locations", } @@ -7720,15 +16762,17 @@ def test_cancel_operation_from_dict(): @pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): +async def test_list_locations_from_dict_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.cancel_operation( + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( request={ "name": "locations", } @@ -7736,39 +16780,41 @@ async def test_cancel_operation_from_dict_async(): call.assert_called() -def test_cancel_operation_flattened(): +def test_list_locations_flattened(): client = LustreClient( 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: + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = locations_pb2.ListLocationsResponse() - client.cancel_operation() + client.list_locations() # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.CancelOperationRequest() + assert args[0] == locations_pb2.ListLocationsRequest() @pytest.mark.asyncio -async def test_cancel_operation_flattened_async(): +async def test_list_locations_flattened_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.cancel_operation() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations() # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.CancelOperationRequest() + assert args[0] == locations_pb2.ListLocationsRequest() -def test_get_operation(transport: str = "grpc"): +def test_get_location(transport: str = "grpc"): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7776,24 +16822,24 @@ def test_get_operation(transport: str = "grpc"): # Everything is optional 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() + request = locations_pb2.GetLocationRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + with mock.patch.object(type(client.transport.get_location), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) + call.return_value = locations_pb2.Location() + response = client.get_location(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) + assert isinstance(response, locations_pb2.Location) @pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc_asyncio"): +async def test_get_location_async(transport: str = "grpc_asyncio"): client = LustreAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -7801,39 +16847,37 @@ async def test_get_operation_async(transport: str = "grpc_asyncio"): # Everything is optional 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() + request = locations_pb2.GetLocationRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + with mock.patch.object(type(client.transport.get_location), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() + locations_pb2.Location() ) - response = await client.get_operation(request) + response = await client.get_location(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) + assert isinstance(response, locations_pb2.Location) -def test_get_operation_field_headers(): - client = LustreClient( - credentials=ga_credentials.AnonymousCredentials(), - ) +def test_get_location_field_headers(): + client = LustreClient(credentials=ga_credentials.AnonymousCredentials()) # Any value 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" + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() - client.get_operation(request) + client.get_location(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] @@ -7843,27 +16887,25 @@ def test_get_operation_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=locations", + "name=locations/abc", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - client = LustreAsyncClient( - credentials=async_anonymous_credentials(), - ) +async def test_get_location_field_headers_async(): + client = LustreAsyncClient(credentials=async_anonymous_credentials()) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + with mock.patch.object(type(client.transport.get_location), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() + locations_pb2.Location() ) - await client.get_operation(request) + await client.get_location(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] @@ -7873,39 +16915,39 @@ async def test_get_operation_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=locations", + "name=locations/abc", ) in kw["metadata"] -def test_get_operation_from_dict(): +def test_get_location_from_dict(): client = LustreClient( 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: + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() + call.return_value = locations_pb2.Location() - response = client.get_operation( + response = client.get_location( request={ - "name": "locations", + "name": "locations/abc", } ) call.assert_called() @pytest.mark.asyncio -async def test_get_operation_from_dict_async(): +async def test_get_location_from_dict_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() + locations_pb2.Location() ) - response = await client.get_operation( + response = await client.get_location( request={ "name": "locations", } @@ -7913,41 +16955,41 @@ async def test_get_operation_from_dict_async(): call.assert_called() -def test_get_operation_flattened(): +def test_get_location_flattened(): client = LustreClient( 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: + with mock.patch.object(type(client.transport.get_location), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() + call.return_value = locations_pb2.Location() - client.get_operation() + client.get_location() # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.GetOperationRequest() + assert args[0] == locations_pb2.GetLocationRequest() @pytest.mark.asyncio -async def test_get_operation_flattened_async(): +async def test_get_location_flattened_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + with mock.patch.object(type(client.transport.get_location), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() + locations_pb2.Location() ) - await client.get_operation() + await client.get_location() # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.GetOperationRequest() + assert args[0] == locations_pb2.GetLocationRequest() -def test_list_operations(transport: str = "grpc"): +def test_set_iam_policy(transport: str = "grpc"): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7955,24 +16997,32 @@ def test_list_operations(transport: str = "grpc"): # Everything is optional 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() + request = iam_policy_pb2.SetIamPolicyRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) + 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, operations_pb2.ListOperationsResponse) + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" @pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc_asyncio"): +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): client = LustreAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -7980,39 +17030,49 @@ async def test_list_operations_async(transport: str = "grpc_asyncio"): # Everything is optional 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() + request = iam_policy_pb2.SetIamPolicyRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + 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( - operations_pb2.ListOperationsResponse() + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) ) - response = await client.list_operations(request) + 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, operations_pb2.ListOperationsResponse) + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 -def test_list_operations_field_headers(): + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value 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" + 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.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) - client.list_operations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] @@ -8022,27 +17082,27 @@ def test_list_operations_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=locations", + "resource=resource/value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_operations_field_headers_async(): +async def test_set_iam_policy_field_headers_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" + 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.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(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] @@ -8052,81 +17112,83 @@ async def test_list_operations_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=locations", + "resource=resource/value", ) in kw["metadata"] -def test_list_operations_from_dict(): +def test_set_iam_policy_from_dict(): client = LustreClient( 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: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() + call.return_value = policy_pb2.Policy() - response = client.list_operations( + response = client.set_iam_policy( request={ - "name": "locations", + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), } ) call.assert_called() @pytest.mark.asyncio -async def test_list_operations_from_dict_async(): +async def test_set_iam_policy_from_dict_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + 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( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.set_iam_policy( request={ - "name": "locations", + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), } ) call.assert_called() -def test_list_operations_flattened(): +def test_set_iam_policy_flattened(): client = LustreClient( 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: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() + call.return_value = policy_pb2.Policy() + + client.set_iam_policy() - client.list_operations() # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.ListOperationsRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() @pytest.mark.asyncio -async def test_list_operations_flattened_async(): +async def test_set_iam_policy_flattened_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + 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( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy() + # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == operations_pb2.ListOperationsRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() -def test_list_locations(transport: str = "grpc"): +def test_get_iam_policy(transport: str = "grpc"): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8134,24 +17196,34 @@ def test_list_locations(transport: str = "grpc"): # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() + request = iam_policy_pb2.GetIamPolicyRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(request) + 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, locations_pb2.ListLocationsResponse) + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" @pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc_asyncio"): +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): client = LustreAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -8159,39 +17231,50 @@ async def test_list_locations_async(transport: str = "grpc_asyncio"): # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() + request = iam_policy_pb2.GetIamPolicyRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + 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( - locations_pb2.ListLocationsResponse() + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) ) - response = await client.list_locations(request) + + response = await client.get_iam_policy(request) + # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 + 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, locations_pb2.ListLocationsResponse) + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 -def test_list_locations_field_headers(): + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" + 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.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) - client.list_locations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] @@ -8201,29 +17284,29 @@ def test_list_locations_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=locations", + "resource=resource/value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_locations_field_headers_async(): +async def test_get_iam_policy_field_headers_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" + 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.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(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) == 1 + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] assert args[0] == request @@ -8231,81 +17314,83 @@ async def test_list_locations_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=locations", + "resource=resource/value", ) in kw["metadata"] -def test_list_locations_from_dict(): +def test_get_iam_policy_from_dict(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() + call.return_value = policy_pb2.Policy() - response = client.list_locations( + response = client.get_iam_policy( request={ - "name": "locations", + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), } ) call.assert_called() @pytest.mark.asyncio -async def test_list_locations_from_dict_async(): +async def test_get_iam_policy_from_dict_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + 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( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.get_iam_policy( request={ - "name": "locations", + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), } ) call.assert_called() -def test_list_locations_flattened(): +def test_get_iam_policy_flattened(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() + call.return_value = policy_pb2.Policy() + + client.get_iam_policy() - client.list_locations() # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == locations_pb2.ListLocationsRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() @pytest.mark.asyncio -async def test_list_locations_flattened_async(): +async def test_get_iam_policy_flattened_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + 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( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy() + # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == locations_pb2.ListLocationsRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() -def test_get_location(transport: str = "grpc"): +def test_test_iam_permissions(transport: str = "grpc"): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8313,24 +17398,33 @@ def test_get_location(transport: str = "grpc"): # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(request) + 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, locations_pb2.Location) + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] @pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): client = LustreAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -8338,37 +17432,51 @@ async def test_get_location_async(transport: str = "grpc_asyncio"): # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: + 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( - locations_pb2.Location() + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) ) - response = await client.get_location(request) + + response = await client.test_iam_permissions(request) + # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 + 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, locations_pb2.Location) + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ["permissions_value"] -def test_get_location_field_headers(): - client = LustreClient(credentials=ga_credentials.AnonymousCredentials()) + +def test_test_iam_permissions_field_headers(): + client = LustreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" + 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.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() + 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) - client.get_location(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] @@ -8378,27 +17486,33 @@ def test_get_location_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=locations/abc", + "resource=resource/value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = LustreAsyncClient(credentials=async_anonymous_credentials()) +async def test_test_iam_permissions_field_headers_async(): + client = LustreAsyncClient( + credentials=async_anonymous_credentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" + 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.get_location), "__call__") as call: + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() + iam_policy_pb2.TestIamPermissionsResponse() ) - await client.get_location(request) + + await client.test_iam_permissions(request) + # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] assert args[0] == request @@ -8406,78 +17520,92 @@ async def test_get_location_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=locations/abc", + "resource=resource/value", ) in kw["metadata"] -def test_get_location_from_dict(): +def test_test_iam_permissions_from_dict(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - response = client.get_location( + response = client.test_iam_permissions( request={ - "name": "locations/abc", + "resource": "resource_value", + "permissions": ["permissions_value"], } ) call.assert_called() @pytest.mark.asyncio -async def test_get_location_from_dict_async(): +async def test_test_iam_permissions_from_dict_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + 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( - locations_pb2.Location() + iam_policy_pb2.TestIamPermissionsResponse() ) - response = await client.get_location( + + response = await client.test_iam_permissions( request={ - "name": "locations", + "resource": "resource_value", + "permissions": ["permissions_value"], } ) call.assert_called() -def test_get_location_flattened(): +def test_test_iam_permissions_flattened(): client = LustreClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions() - client.get_location() # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == locations_pb2.GetLocationRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() @pytest.mark.asyncio -async def test_get_location_flattened_async(): +async def test_test_iam_permissions_flattened_async(): client = LustreAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: + 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( - locations_pb2.Location() + iam_policy_pb2.TestIamPermissionsResponse() ) - await client.get_location() + + await client.test_iam_permissions() + # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == locations_pb2.GetLocationRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() def test_transport_close_grpc(): diff --git a/packages/google-cloud-monitoring-dashboards/google/cloud/monitoring_dashboard_v1/types/incident_list.py b/packages/google-cloud-monitoring-dashboards/google/cloud/monitoring_dashboard_v1/types/incident_list.py index 9563290c9a45..a3a57190c5af 100644 --- a/packages/google-cloud-monitoring-dashboards/google/cloud/monitoring_dashboard_v1/types/incident_list.py +++ b/packages/google-cloud-monitoring-dashboards/google/cloud/monitoring_dashboard_v1/types/incident_list.py @@ -29,20 +29,20 @@ class IncidentList(proto.Message): - r"""A widget that displays a list of incidents + r"""A widget that displays a list of alerts Attributes: monitored_resources (MutableSequence[google.api.monitored_resource_pb2.MonitoredResource]): Optional. The monitored resource for which - incidents are listed. The resource doesn't need - to be fully specified. That is, you can specify - the resource type but not the values of the - resource labels. The resource type and labels - are used for filtering. + alerts are listed. The resource doesn't need to + be fully specified. That is, you can specify the + resource type but not the values of the resource + labels. The resource type and labels are used + for filtering. policy_names (MutableSequence[str]): - Optional. A list of alert policy names to filter the - incident list by. Don't include the project ID prefix in the - policy name. For example, use ``alertPolicies/utilization``. + Optional. A list of alert policy names to filter the alert + list by. Don't include the project ID prefix in the policy + name. For example, use ``alertPolicies/utilization``. """ monitored_resources: MutableSequence[monitored_resource_pb2.MonitoredResource] = ( diff --git a/packages/google-cloud-monitoring-dashboards/google/cloud/monitoring_dashboard_v1/types/widget.py b/packages/google-cloud-monitoring-dashboards/google/cloud/monitoring_dashboard_v1/types/widget.py index 7b2f9b84f4c5..12077170e8cb 100644 --- a/packages/google-cloud-monitoring-dashboards/google/cloud/monitoring_dashboard_v1/types/widget.py +++ b/packages/google-cloud-monitoring-dashboards/google/cloud/monitoring_dashboard_v1/types/widget.py @@ -104,7 +104,7 @@ class Widget(proto.Message): This field is a member of `oneof`_ ``content``. incident_list (google.cloud.monitoring_dashboard_v1.types.IncidentList): - A widget that shows list of incidents. + A widget that shows list of alerts. This field is a member of `oneof`_ ``content``. pie_chart (google.cloud.monitoring_dashboard_v1.types.PieChart): diff --git a/packages/google-cloud-parametermanager/google/cloud/parametermanager/__init__.py b/packages/google-cloud-parametermanager/google/cloud/parametermanager/__init__.py index 74211fa3c610..89eecda0d19f 100644 --- a/packages/google-cloud-parametermanager/google/cloud/parametermanager/__init__.py +++ b/packages/google-cloud-parametermanager/google/cloud/parametermanager/__init__.py @@ -27,22 +27,40 @@ from google.cloud.parametermanager_v1.types.service import ( CreateParameterRequest, CreateParameterVersionRequest, + CreateTemplateRequest, + CreateTemplateVersionRequest, DeleteParameterRequest, DeleteParameterVersionRequest, + DeleteTemplateRequest, + DeleteTemplateVersionRequest, GetParameterRequest, GetParameterVersionRequest, + GetTemplateRequest, + GetTemplateVersionRequest, ListParametersRequest, ListParametersResponse, ListParameterVersionsRequest, ListParameterVersionsResponse, + ListTemplatesRequest, + ListTemplatesResponse, + ListTemplateVersionsRequest, + ListTemplateVersionsResponse, Parameter, ParameterFormat, ParameterVersion, ParameterVersionPayload, RenderParameterVersionRequest, RenderParameterVersionResponse, + RenderTemplateVersionRequest, + RenderTemplateVersionResponse, + Template, + TemplateFormat, + TemplateVersion, + TemplateVersionPayload, UpdateParameterRequest, UpdateParameterVersionRequest, + UpdateTemplateRequest, + UpdateTemplateVersionRequest, View, ) @@ -51,21 +69,39 @@ "ParameterManagerAsyncClient", "CreateParameterRequest", "CreateParameterVersionRequest", + "CreateTemplateRequest", + "CreateTemplateVersionRequest", "DeleteParameterRequest", "DeleteParameterVersionRequest", + "DeleteTemplateRequest", + "DeleteTemplateVersionRequest", "GetParameterRequest", "GetParameterVersionRequest", + "GetTemplateRequest", + "GetTemplateVersionRequest", "ListParametersRequest", "ListParametersResponse", "ListParameterVersionsRequest", "ListParameterVersionsResponse", + "ListTemplatesRequest", + "ListTemplatesResponse", + "ListTemplateVersionsRequest", + "ListTemplateVersionsResponse", "Parameter", "ParameterVersion", "ParameterVersionPayload", "RenderParameterVersionRequest", "RenderParameterVersionResponse", + "RenderTemplateVersionRequest", + "RenderTemplateVersionResponse", + "Template", + "TemplateVersion", + "TemplateVersionPayload", "UpdateParameterRequest", "UpdateParameterVersionRequest", + "UpdateTemplateRequest", + "UpdateTemplateVersionRequest", "ParameterFormat", + "TemplateFormat", "View", ) diff --git a/packages/google-cloud-parametermanager/google/cloud/parametermanager_v1/__init__.py b/packages/google-cloud-parametermanager/google/cloud/parametermanager_v1/__init__.py index 220a30abd9af..715a9dfa8eb1 100644 --- a/packages/google-cloud-parametermanager/google/cloud/parametermanager_v1/__init__.py +++ b/packages/google-cloud-parametermanager/google/cloud/parametermanager_v1/__init__.py @@ -38,22 +38,40 @@ from .types.service import ( CreateParameterRequest, CreateParameterVersionRequest, + CreateTemplateRequest, + CreateTemplateVersionRequest, DeleteParameterRequest, DeleteParameterVersionRequest, + DeleteTemplateRequest, + DeleteTemplateVersionRequest, GetParameterRequest, GetParameterVersionRequest, + GetTemplateRequest, + GetTemplateVersionRequest, ListParametersRequest, ListParametersResponse, ListParameterVersionsRequest, ListParameterVersionsResponse, + ListTemplatesRequest, + ListTemplatesResponse, + ListTemplateVersionsRequest, + ListTemplateVersionsResponse, Parameter, ParameterFormat, ParameterVersion, ParameterVersionPayload, RenderParameterVersionRequest, RenderParameterVersionResponse, + RenderTemplateVersionRequest, + RenderTemplateVersionResponse, + Template, + TemplateFormat, + TemplateVersion, + TemplateVersionPayload, UpdateParameterRequest, UpdateParameterVersionRequest, + UpdateTemplateRequest, + UpdateTemplateVersionRequest, View, ) @@ -61,14 +79,24 @@ "ParameterManagerAsyncClient", "CreateParameterRequest", "CreateParameterVersionRequest", + "CreateTemplateRequest", + "CreateTemplateVersionRequest", "DeleteParameterRequest", "DeleteParameterVersionRequest", + "DeleteTemplateRequest", + "DeleteTemplateVersionRequest", "GetParameterRequest", "GetParameterVersionRequest", + "GetTemplateRequest", + "GetTemplateVersionRequest", "ListParameterVersionsRequest", "ListParameterVersionsResponse", "ListParametersRequest", "ListParametersResponse", + "ListTemplateVersionsRequest", + "ListTemplateVersionsResponse", + "ListTemplatesRequest", + "ListTemplatesResponse", "Parameter", "ParameterFormat", "ParameterManagerClient", @@ -76,8 +104,16 @@ "ParameterVersionPayload", "RenderParameterVersionRequest", "RenderParameterVersionResponse", + "RenderTemplateVersionRequest", + "RenderTemplateVersionResponse", + "Template", + "TemplateFormat", + "TemplateVersion", + "TemplateVersionPayload", "UpdateParameterRequest", "UpdateParameterVersionRequest", + "UpdateTemplateRequest", + "UpdateTemplateVersionRequest", "View", ) diff --git a/packages/google-cloud-parametermanager/google/cloud/parametermanager_v1/gapic_metadata.json b/packages/google-cloud-parametermanager/google/cloud/parametermanager_v1/gapic_metadata.json index 568749c460ba..5db34ad8b299 100644 --- a/packages/google-cloud-parametermanager/google/cloud/parametermanager_v1/gapic_metadata.json +++ b/packages/google-cloud-parametermanager/google/cloud/parametermanager_v1/gapic_metadata.json @@ -20,6 +20,16 @@ "create_parameter_version" ] }, + "CreateTemplate": { + "methods": [ + "create_template" + ] + }, + "CreateTemplateVersion": { + "methods": [ + "create_template_version" + ] + }, "DeleteParameter": { "methods": [ "delete_parameter" @@ -30,6 +40,16 @@ "delete_parameter_version" ] }, + "DeleteTemplate": { + "methods": [ + "delete_template" + ] + }, + "DeleteTemplateVersion": { + "methods": [ + "delete_template_version" + ] + }, "GetParameter": { "methods": [ "get_parameter" @@ -40,6 +60,16 @@ "get_parameter_version" ] }, + "GetTemplate": { + "methods": [ + "get_template" + ] + }, + "GetTemplateVersion": { + "methods": [ + "get_template_version" + ] + }, "ListParameterVersions": { "methods": [ "list_parameter_versions" @@ -50,11 +80,26 @@ "list_parameters" ] }, + "ListTemplateVersions": { + "methods": [ + "list_template_versions" + ] + }, + "ListTemplates": { + "methods": [ + "list_templates" + ] + }, "RenderParameterVersion": { "methods": [ "render_parameter_version" ] }, + "RenderTemplateVersion": { + "methods": [ + "render_template_version" + ] + }, "UpdateParameter": { "methods": [ "update_parameter" @@ -64,6 +109,16 @@ "methods": [ "update_parameter_version" ] + }, + "UpdateTemplate": { + "methods": [ + "update_template" + ] + }, + "UpdateTemplateVersion": { + "methods": [ + "update_template_version" + ] } } }, @@ -80,6 +135,16 @@ "create_parameter_version" ] }, + "CreateTemplate": { + "methods": [ + "create_template" + ] + }, + "CreateTemplateVersion": { + "methods": [ + "create_template_version" + ] + }, "DeleteParameter": { "methods": [ "delete_parameter" @@ -90,6 +155,16 @@ "delete_parameter_version" ] }, + "DeleteTemplate": { + "methods": [ + "delete_template" + ] + }, + "DeleteTemplateVersion": { + "methods": [ + "delete_template_version" + ] + }, "GetParameter": { "methods": [ "get_parameter" @@ -100,6 +175,16 @@ "get_parameter_version" ] }, + "GetTemplate": { + "methods": [ + "get_template" + ] + }, + "GetTemplateVersion": { + "methods": [ + "get_template_version" + ] + }, "ListParameterVersions": { "methods": [ "list_parameter_versions" @@ -110,11 +195,26 @@ "list_parameters" ] }, + "ListTemplateVersions": { + "methods": [ + "list_template_versions" + ] + }, + "ListTemplates": { + "methods": [ + "list_templates" + ] + }, "RenderParameterVersion": { "methods": [ "render_parameter_version" ] }, + "RenderTemplateVersion": { + "methods": [ + "render_template_version" + ] + }, "UpdateParameter": { "methods": [ "update_parameter" @@ -124,6 +224,16 @@ "methods": [ "update_parameter_version" ] + }, + "UpdateTemplate": { + "methods": [ + "update_template" + ] + }, + "UpdateTemplateVersion": { + "methods": [ + "update_template_version" + ] } } }, @@ -140,6 +250,16 @@ "create_parameter_version" ] }, + "CreateTemplate": { + "methods": [ + "create_template" + ] + }, + "CreateTemplateVersion": { + "methods": [ + "create_template_version" + ] + }, "DeleteParameter": { "methods": [ "delete_parameter" @@ -150,6 +270,16 @@ "delete_parameter_version" ] }, + "DeleteTemplate": { + "methods": [ + "delete_template" + ] + }, + "DeleteTemplateVersion": { + "methods": [ + "delete_template_version" + ] + }, "GetParameter": { "methods": [ "get_parameter" @@ -160,6 +290,16 @@ "get_parameter_version" ] }, + "GetTemplate": { + "methods": [ + "get_template" + ] + }, + "GetTemplateVersion": { + "methods": [ + "get_template_version" + ] + }, "ListParameterVersions": { "methods": [ "list_parameter_versions" @@ -170,11 +310,26 @@ "list_parameters" ] }, + "ListTemplateVersions": { + "methods": [ + "list_template_versions" + ] + }, + "ListTemplates": { + "methods": [ + "list_templates" + ] + }, "RenderParameterVersion": { "methods": [ "render_parameter_version" ] }, + "RenderTemplateVersion": { + "methods": [ + "render_template_version" + ] + }, "UpdateParameter": { "methods": [ "update_parameter" @@ -184,6 +339,16 @@ "methods": [ "update_parameter_version" ] + }, + "UpdateTemplate": { + "methods": [ + "update_template" + ] + }, + "UpdateTemplateVersion": { + "methods": [ + "update_template_version" + ] } } } diff --git a/packages/google-cloud-parametermanager/google/cloud/parametermanager_v1/services/parameter_manager/async_client.py b/packages/google-cloud-parametermanager/google/cloud/parametermanager_v1/services/parameter_manager/async_client.py index c8aadf41f227..ce8e80910b35 100644 --- a/packages/google-cloud-parametermanager/google/cloud/parametermanager_v1/services/parameter_manager/async_client.py +++ b/packages/google-cloud-parametermanager/google/cloud/parametermanager_v1/services/parameter_manager/async_client.py @@ -86,6 +86,12 @@ class ParameterManagerAsyncClient: parse_parameter_version_path = staticmethod( ParameterManagerClient.parse_parameter_version_path ) + template_path = staticmethod(ParameterManagerClient.template_path) + parse_template_path = staticmethod(ParameterManagerClient.parse_template_path) + template_version_path = staticmethod(ParameterManagerClient.template_version_path) + parse_template_version_path = staticmethod( + ParameterManagerClient.parse_template_version_path + ) common_billing_account_path = staticmethod( ParameterManagerClient.common_billing_account_path ) @@ -1606,6 +1612,1304 @@ async def sample_delete_parameter_version(): metadata=metadata, ) + async def list_templates( + self, + request: Optional[Union[service.ListTemplatesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListTemplatesAsyncPager: + r"""Lists Templates in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import parametermanager_v1 + + async def sample_list_templates(): + # Create a client + client = parametermanager_v1.ParameterManagerAsyncClient() + + # Initialize request argument(s) + request = parametermanager_v1.ListTemplatesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_templates(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.parametermanager_v1.types.ListTemplatesRequest, dict]]): + The request object. Message for requesting list of + Templates + parent (:class:`str`): + Required. Parent value for ListTemplatesRequest in the + format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.parametermanager_v1.services.parameter_manager.pagers.ListTemplatesAsyncPager: + Message for response to listing + Templates + 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. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListTemplatesRequest): + request = service.ListTemplatesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_templates + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTemplatesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_template( + self, + request: Optional[Union[service.GetTemplateRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.Template: + r"""Gets details of a single Template. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import parametermanager_v1 + + async def sample_get_template(): + # Create a client + client = parametermanager_v1.ParameterManagerAsyncClient() + + # Initialize request argument(s) + request = parametermanager_v1.GetTemplateRequest( + name="name_value", + ) + + # Make the request + response = await client.get_template(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.parametermanager_v1.types.GetTemplateRequest, dict]]): + The request object. Message for getting a Template + name (:class:`str`): + Required. Name of the resource in the format + ``projects/*/locations/*/templates/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.parametermanager_v1.types.Template: + Message describing Template resource + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetTemplateRequest): + request = service.GetTemplateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_template + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_template( + self, + request: Optional[Union[service.CreateTemplateRequest, dict]] = None, + *, + parent: Optional[str] = None, + template: Optional[service.Template] = None, + template_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.Template: + r"""Creates a new Template in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import parametermanager_v1 + + async def sample_create_template(): + # Create a client + client = parametermanager_v1.ParameterManagerAsyncClient() + + # Initialize request argument(s) + request = parametermanager_v1.CreateTemplateRequest( + parent="parent_value", + template_id="template_id_value", + ) + + # Make the request + response = await client.create_template(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.parametermanager_v1.types.CreateTemplateRequest, dict]]): + The request object. Message for creating a Template + parent (:class:`str`): + Required. Value for parent in the format + ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + template (:class:`google.cloud.parametermanager_v1.types.Template`): + Required. The Template resource being + created + + This corresponds to the ``template`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + template_id (:class:`str`): + Required. Id of the Template resource + This corresponds to the ``template_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.parametermanager_v1.types.Template: + Message describing Template resource + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, template, template_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateTemplateRequest): + request = service.CreateTemplateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if template is not None: + request.template = template + if template_id is not None: + request.template_id = template_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_template + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_template( + self, + request: Optional[Union[service.UpdateTemplateRequest, dict]] = None, + *, + template: Optional[service.Template] = 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, Union[str, bytes]]] = (), + ) -> service.Template: + r"""Updates a single Template. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import parametermanager_v1 + + async def sample_update_template(): + # Create a client + client = parametermanager_v1.ParameterManagerAsyncClient() + + # Initialize request argument(s) + request = parametermanager_v1.UpdateTemplateRequest( + ) + + # Make the request + response = await client.update_template(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.parametermanager_v1.types.UpdateTemplateRequest, dict]]): + The request object. Message for updating a Template + template (:class:`google.cloud.parametermanager_v1.types.Template`): + Required. The Template resource being + updated + + This corresponds to the ``template`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the Template resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A mutable field will be + overwritten if it is in the mask. If the user does not + provide a mask then all mutable fields present in the + request will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.parametermanager_v1.types.Template: + Message describing Template resource + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [template, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateTemplateRequest): + request = service.UpdateTemplateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if template is not None: + request.template = template + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_template + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("template.name", request.template.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_template( + self, + request: Optional[Union[service.DeleteTemplateRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a single Template. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import parametermanager_v1 + + async def sample_delete_template(): + # Create a client + client = parametermanager_v1.ParameterManagerAsyncClient() + + # Initialize request argument(s) + request = parametermanager_v1.DeleteTemplateRequest( + name="name_value", + ) + + # Make the request + await client.delete_template(request=request) + + Args: + request (Optional[Union[google.cloud.parametermanager_v1.types.DeleteTemplateRequest, dict]]): + The request object. Message for deleting a Template + name (:class:`str`): + Required. Name of the resource in the format + ``projects/*/locations/*/templates/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DeleteTemplateRequest): + request = service.DeleteTemplateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_template + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_template_versions( + self, + request: Optional[Union[service.ListTemplateVersionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListTemplateVersionsAsyncPager: + r"""Lists TemplateVersions in a given project, location, + and template. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import parametermanager_v1 + + async def sample_list_template_versions(): + # Create a client + client = parametermanager_v1.ParameterManagerAsyncClient() + + # Initialize request argument(s) + request = parametermanager_v1.ListTemplateVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_template_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.parametermanager_v1.types.ListTemplateVersionsRequest, dict]]): + The request object. Message for requesting list of + TemplateVersions + parent (:class:`str`): + Required. Parent value for ListTemplateVersionsRequest + in the format ``projects/*/locations/*/templates/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.parametermanager_v1.services.parameter_manager.pagers.ListTemplateVersionsAsyncPager: + Message for response to listing + TemplateVersions + 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. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListTemplateVersionsRequest): + request = service.ListTemplateVersionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_template_versions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTemplateVersionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_template_version( + self, + request: Optional[Union[service.GetTemplateVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.TemplateVersion: + r"""Gets details of a single TemplateVersion. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import parametermanager_v1 + + async def sample_get_template_version(): + # Create a client + client = parametermanager_v1.ParameterManagerAsyncClient() + + # Initialize request argument(s) + request = parametermanager_v1.GetTemplateVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_template_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.parametermanager_v1.types.GetTemplateVersionRequest, dict]]): + The request object. Message for getting a TemplateVersion + name (:class:`str`): + Required. Name of the resource in the format + ``projects/*/locations/*/templates/*/versions/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.parametermanager_v1.types.TemplateVersion: + Message describing TemplateVersion + resource + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetTemplateVersionRequest): + request = service.GetTemplateVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_template_version + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_template_version( + self, + request: Optional[Union[service.CreateTemplateVersionRequest, dict]] = None, + *, + parent: Optional[str] = None, + template_version: Optional[service.TemplateVersion] = None, + template_version_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.TemplateVersion: + r"""Creates a new TemplateVersion in a given project, + location, and template. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import parametermanager_v1 + + async def sample_create_template_version(): + # Create a client + client = parametermanager_v1.ParameterManagerAsyncClient() + + # Initialize request argument(s) + template_version = parametermanager_v1.TemplateVersion() + template_version.payload.data = b'data_blob' + + request = parametermanager_v1.CreateTemplateVersionRequest( + parent="parent_value", + template_version_id="template_version_id_value", + template_version=template_version, + ) + + # Make the request + response = await client.create_template_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.parametermanager_v1.types.CreateTemplateVersionRequest, dict]]): + The request object. Message for creating a + TemplateVersion + parent (:class:`str`): + Required. Value for parent in the format + ``projects/*/locations/*/templates/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + template_version (:class:`google.cloud.parametermanager_v1.types.TemplateVersion`): + Required. The TemplateVersion + resource being created + + This corresponds to the ``template_version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + template_version_id (:class:`str`): + Required. Id of the TemplateVersion + resource + + This corresponds to the ``template_version_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.parametermanager_v1.types.TemplateVersion: + Message describing TemplateVersion + resource + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, template_version, template_version_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateTemplateVersionRequest): + request = service.CreateTemplateVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if template_version is not None: + request.template_version = template_version + if template_version_id is not None: + request.template_version_id = template_version_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_template_version + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_template_version( + self, + request: Optional[Union[service.UpdateTemplateVersionRequest, dict]] = None, + *, + template_version: Optional[service.TemplateVersion] = 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, Union[str, bytes]]] = (), + ) -> service.TemplateVersion: + r"""Updates a single TemplateVersion. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import parametermanager_v1 + + async def sample_update_template_version(): + # Create a client + client = parametermanager_v1.ParameterManagerAsyncClient() + + # Initialize request argument(s) + template_version = parametermanager_v1.TemplateVersion() + template_version.payload.data = b'data_blob' + + request = parametermanager_v1.UpdateTemplateVersionRequest( + template_version=template_version, + ) + + # Make the request + response = await client.update_template_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.parametermanager_v1.types.UpdateTemplateVersionRequest, dict]]): + The request object. Message for updating a + TemplateVersion + template_version (:class:`google.cloud.parametermanager_v1.types.TemplateVersion`): + Required. The TemplateVersion + resource being updated + + This corresponds to the ``template_version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the TemplateVersion resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A + mutable field will be overwritten if it is in the mask. + If the user does not provide a mask then all mutable + fields present in the request will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.parametermanager_v1.types.TemplateVersion: + Message describing TemplateVersion + resource + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [template_version, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateTemplateVersionRequest): + request = service.UpdateTemplateVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if template_version is not None: + request.template_version = template_version + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_template_version + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("template_version.name", request.template_version.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_template_version( + self, + request: Optional[Union[service.DeleteTemplateVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a single TemplateVersion. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import parametermanager_v1 + + async def sample_delete_template_version(): + # Create a client + client = parametermanager_v1.ParameterManagerAsyncClient() + + # Initialize request argument(s) + request = parametermanager_v1.DeleteTemplateVersionRequest( + name="name_value", + ) + + # Make the request + await client.delete_template_version(request=request) + + Args: + request (Optional[Union[google.cloud.parametermanager_v1.types.DeleteTemplateVersionRequest, dict]]): + The request object. Message for deleting a + TemplateVersion + name (:class:`str`): + Required. Name of the resource in the format + ``projects/*/locations/*/templates/*/versions/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DeleteTemplateVersionRequest): + request = service.DeleteTemplateVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_template_version + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def render_template_version( + self, + request: Optional[Union[service.RenderTemplateVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.RenderTemplateVersionResponse: + r"""Gets rendered version of a TemplateVersion. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import parametermanager_v1 + + async def sample_render_template_version(): + # Create a client + client = parametermanager_v1.ParameterManagerAsyncClient() + + # Initialize request argument(s) + request = parametermanager_v1.RenderTemplateVersionRequest( + name="name_value", + parameter_version="parameter_version_value", + ) + + # Make the request + response = await client.render_template_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.parametermanager_v1.types.RenderTemplateVersionRequest, dict]]): + The request object. Message describing + RenderTemplateVersionRequest resource + name (:class:`str`): + Required. Name of the 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_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.parametermanager_v1.types.RenderTemplateVersionResponse: + Message describing + RenderTemplateVersionResponse resource + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.RenderTemplateVersionRequest): + request = service.RenderTemplateVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.render_template_version + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def get_location( self, request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, diff --git a/packages/google-cloud-parametermanager/google/cloud/parametermanager_v1/services/parameter_manager/client.py b/packages/google-cloud-parametermanager/google/cloud/parametermanager_v1/services/parameter_manager/client.py index b1e3e1cc388b..64e2317081a7 100644 --- a/packages/google-cloud-parametermanager/google/cloud/parametermanager_v1/services/parameter_manager/client.py +++ b/packages/google-cloud-parametermanager/google/cloud/parametermanager_v1/services/parameter_manager/client.py @@ -244,6 +244,52 @@ def parse_parameter_version_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def template_path( + project: str, + location: str, + template: str, + ) -> str: + """Returns a fully-qualified template string.""" + return "projects/{project}/locations/{location}/templates/{template}".format( + project=project, + location=location, + template=template, + ) + + @staticmethod + def parse_template_path(path: str) -> Dict[str, str]: + """Parses a template path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/templates/(?P